package com.cqupt.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.cqupt.mapper.HostMapper;
import com.cqupt.pojo.Host;
import com.cqupt.service.HostService;
import com.cqupt.service.ItemService;
import com.cqupt.service.MonitorService;
import com.cqupt.utils.*;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.FileOutputStream;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author ：
 * @date ：Created in 2020/11/25 9:05
 * @description：
 * @modified By：
 */
@Service
public class MonitorServiceImpl implements MonitorService {
    private HostMapper hostMapper;

    public HostMapper getHostMapper() {
        return hostMapper;
    }
    @Autowired
    public void setHostMapper(HostMapper hostMapper) {
        this.hostMapper = hostMapper;
    }

    @Autowired
    private HostService hostService;

    @Autowired
    private ItemService itemService;
    /**
     * 根据用户id获得登录的主机名和密码
     * @param hostId
     * @return
     */
    @Override
    public Map<String,Object> getusernamepwdbyHostid(String hostId) {
        // 通过主机hostid获得用户名
        Host host = hostMapper.getUserById(hostId);
        Map<String,Object> usernameandpwd = new HashMap<>();
        usernameandpwd = null;
        if(host != null){
            String userName = host.getUserName();
            String password = host.getPassword();
            if(userName != null && password != null){
                usernameandpwd.put("username",userName);
                usernameandpwd.put("password",password);
            }
        }
        return usernameandpwd;
    }

    /**
     *
     * @description: 分页
     * @param:
     * @return:
     * @author:
     * @time:
     */
    public List<Map<String, Object>> getPagingData(List<Map<String, Object>> list,Integer pageNo, Integer pageSize){
        int count = list.size();
        int pageStart = (pageNo - 1) * pageSize;
        int pageEnd = pageStart + pageSize;
        // 数量不满足一页时，全部展示
        if (((pageNo - 1) * pageSize) <= count) {
            if ((count - pageStart) < pageSize)
                return list.subList(pageStart, count);
            else
                return list.subList(pageStart, pageEnd);
        }else {
            return null;
        }
    }
    //    /**
//     *
//     * @description: 监控设备总表
//     * @param:
//     * @return:
//     * @author:
//     * @time:
//     * @param
//     * @param pageNo
//     * @param pageSize
//     * @param status
//     */
/*    @Override
    public List<Map<String, Object>> getHostList(Integer pageNo, Integer pageSize, Integer status) {
        final String token = APIUtils.getToken();
//        获得主机详细信息列表
        List<Map<String, Object>> hostList = new DemoServiceImpl().getAllOnlineHost();
        List<Map<String, Object>> hostList_temp = new ArrayList<>();
//        根据状态筛选
        if (status != null){
            for (Map<String, Object> map : hostList) {
                if (map.get("status").toString().equals(status.toString())){
                    hostList_temp.add(map);
                }
            }
            hostList = hostList_temp;
        }
        int hostCount = hostList.size();
//        分页
        int pageStart = (pageNo - 1) * pageSize;
        int pageEnd = pageStart + pageSize;
        if (((pageNo - 1) * pageSize) <= hostCount) {
            if ((hostCount - pageStart) < pageSize)
                hostList = hostList.subList(pageStart, hostCount);
            else
                hostList = hostList.subList(pageStart, pageEnd);
        }else {
            return null;
        }
//        组装主机id数组 ids
        final List<String> hostIds = new ArrayList<>();
        for (Map<String, Object> maps : hostList) {
            hostIds.add((String) maps.get("hostid"));
        }
        Map<String, Object> paramsMap = new HashMap<String, Object>(){{
            put("jsonrpc", "2.0");
            put("method", "hostinterface.get");
            put("id", 1);
            put("auth", token);
            put("params", new HashMap<String, Object>(){{
                put("output","extend");
                put("hostids",hostIds);
            }});
        }};
//        获取主机接口信息列表
        Map<String, Object> hostInterfaceMap = APIUtils.sendRequest(JSON.toJSONString(paramsMap, SerializerFeature.WriteMapNullValue));
        List<Map<String, Object>> hostInterfaceList = (List<Map<String, Object>>)hostInterfaceMap.get("result");
        List<Map<String, Object>> result = new ArrayList<>();
        int offset = 0;
        for (int i = 0; i < hostList.size(); i++){
            Map<String, Object> resultMap = new HashMap<>();
            if (resultMap.get("ip") == null) {
                resultMap.put("ip", hostInterfaceList.get(i+offset).get("ip") + ":" + hostInterfaceList.get(i+offset).get("port"));
            }else {
                offset++;
                continue;
            }
            resultMap.put("hostname", hostList.get(i).get("name"));
            System.out.println(hostList.get(i).get("status"));
            if (hostList.get(i).get("status").toString().equals("0"))
                resultMap.put("status", "已启用");
            else
                resultMap.put("status", "已禁用");
            resultMap.put("hostid", hostList.get(i).get("hostid"));
            result.add(resultMap);
        }
        return result;
    }
*/
//    public List<Map<String, Object>> getHostList(Integer pageNo, Integer pageSize, String status, Integer hostType) {
//        final String token = APIUtils.getToken();
////        获得主机详细信息列表
//        List<Map<String, Object>> hostList = new DemoServiceImpl().getAllOnlineHost();
//        List<Map<String, Object>> ZBXHostList = new ArrayList<>();
//        List<Map<String, Object>> SNMPHostList = new ArrayList<>();
//        for (Map<String, Object> map : hostList) {
//            if(map.get("available").toString().equals("0"))
//                SNMPHostList.add(map);
//            else
//                ZBXHostList.add(map);
//        }
//        if (hostType == 0)
//            hostList = ZBXHostList;
//        else
//            hostList = SNMPHostList;
////        根据状态筛选
//        String status_num = "";
//        if ("已启用".equals(status)) {
//            status_num = "0";
//        }
//        else if ("已禁用".equals(status)) {
//            status_num = "1";
//        }
//        List<Map<String, Object>> hostList_temp = new ArrayList<>();
//        if (status != null && status != ""){
//            for (Map<String, Object> map : hostList) {
//                if (map.get("status").toString().equals(status_num)){
//                    hostList_temp.add(map);
//                }
//            }
//            hostList = hostList_temp;
//        }
////        分页
////        hostList = getPagingData(hostList, pageNo, pageSize);
////        组装主机id数组 ids
//        final List<String> hostIds = new ArrayList<>();
//        final List<String> hosts = new ArrayList<>();
//
//        for (Map<String, Object> maps : hostList) {
//            hostIds.add((String) maps.get("hostid"));
//            hosts.add((String) maps.get("host"));
//        }
////        获取主机接口列表
//        List<Map<String, Object>> hostInterfaceList = getHostInterfaceListByHostIds(hostIds);
//        List<Map<String, Object>> result = new ArrayList<>();
//        int offset = 0;
//        List<Map<String, Object>> importItem = getImportItem();
//        for (int i = 0; i < hostList.size(); i++){
//            List<Map<String, Object>> state = new HostServiceImpl().getHostStatusById(token, hosts.get(i));
//            Map<String, Object> inventory = new HostServiceImpl().getHostInventory(token, hostIds.get(i));
//            List<Map<String, Object>> details = (List<Map<String, Object>>) inventory.get("result");
//            Map<String, Object> res = details.get(0);
//
//            System.out.println("资产清单：" + inventory);
//
//            Map<String, Object> resultMap = new HashMap<>();
//            // 资产清单
//            resultMap.put("inventory", res.get("inventory"));
//            //名称
//            resultMap.put("hostname", hostList.get(i).get("name"));
//            //接口
//            if (resultMap.get("ip") == null) {
//                resultMap.put("ip", hostInterfaceList.get(i + offset).get("ip") + ":" + hostInterfaceList.get(i + offset).get("port"));
//            }else {
//                offset++;
//                continue;
//            }
//
//            //可用性
////            System.out.println(state.get(0).get("available"));
////            System.out.println(state.get(0).get("ipmi_available"));
////            System.out.println(state.get(0).get("jmx_available"));
////            System.out.println(state.get(0).get("snmp_available"));
//            if ("1".equals(state.get(0).get("available"))){
//                resultMap.put("avail","ZBX");
////                System.out.println("ZBX");
//            }
//            else if("2".equals(state.get(0).get("available"))){
//                resultMap.put("avail","ZBX不可用");
////                System.out.println("ZBX不可用");
//            }else {
//                if ("1".equals(state.get(0).get("ipmi_available"))){
//                    resultMap.put("avail","IPMI");
////                    System.out.println("IPMI");
//                }else if("2".equals(state.get(0).get("ipmi_available"))) {
//                    resultMap.put("avail", "IPMI不可用");
////                    System.out.println("IPMI不可用");
//                }else {
//                    if ("1".equals(state.get(0).get("jmx_available"))){
//                        resultMap.put("avail","JMX");
////                        System.out.println("JMX");
//                    }else if("2".equals(state.get(0).get("jmx_available"))) {
//                        resultMap.put("avail", "JMX不可用");
////                        System.out.println("JMX不可用");
//                    }else {
//                        if ("1".equals(state.get(0).get("snmp_available"))){
//                            resultMap.put("avail","SNMP");
////                            System.out.println("SNMP");
//                        }else if("2".equals(state.get(0).get("snmp_available"))) {
//                            resultMap.put("avail", "SNMP不可用");
////                            System.out.println("SNMP不可用");
//                        }else{
//                            resultMap.put("avail","未知");
////                            System.out.println("未知");
//                        }
//                    }
//                }
//            }
//            //状态
//            if (hostList.get(i).get("status").toString().equals("0"))
//                resultMap.put("status", "已启用");
//            else
//                resultMap.put("status", "已禁用");
//            //其余新的添加
//            Map<String, Object> item = null;
//            if (hostType == 0){
//                //服务器
//                item = getImportantItemByHostid(hostList.get(i).get("hostid").toString(), importItem);
//            }else{
//                //交换机
//                item = getSnmpCpuAndMemryByHostid(hostList.get(i).get("hostid").toString());
//            }
//
//            if (item != null){
//                resultMap.put("item", item);
//                resultMap.put("clock", item.get("clock"));
//            }else {
//                resultMap.put("item", "暂未配置相关监控项");
//            }
//            //时间
//
//            resultMap.put("hostid", hostList.get(i).get("hostid"));
//            result.add(resultMap);
//        }
////        System.out.println("++++:" + result);
//        return result;
//    }
    /**
     * 根据hostid获取snmp设备的cpu利用和内存利用率
     * @param hostid
     * @return
     */
    @Override
    public Map<String, Object> getSnmpCpuAndMemryByHostid(String hostid) {
        final String token = APIUtils.getToken();
        Double cputime=0.0;
        Double memorytime=0.0;
        // 通过主机hostid和监控监控项名称获得cpu监控项信息
        List<Map<String, Object>> cpu_utilization = new PortServiceImpl().getItemsByName(token, hostid, "CPU utilization");
        // 通过主机hostid和监控监控项名称获得memory监控项信息
        List<Map<String, Object>> memory_utilization = new PortServiceImpl().getItemsByName(token, hostid, "Memory utilization");
        Map<String, Object> snmpcpu = cpu_utilization.get(0);
        Map<String, Object> snmpmemory = memory_utilization.get(0);
        try {
            // 类型转换String-->Double
            cputime = Double.valueOf(snmpcpu.get("lastclock").toString());
        }
        catch(NullPointerException e){
            cputime = 0.0;
        }
        try {
            // 类型转换String-->Double
            memorytime = Double.valueOf(snmpmemory.get("lastclock").toString());
        }
        catch(NullPointerException e){
            memorytime = 0.0;
        }
        String latesttime = null;
        if(cputime>memorytime){
            // 获得最新的时间
            latesttime = cputime.toString();
        }else{
            // 获得最新的时间
            latesttime = memorytime.toString();
        }
        Map<String,Object> snmpdevice = new HashMap<>();
        if(snmpcpu.get("lastvalue")!=null){
            // 获得最新的值
            snmpdevice.put("CPUUtilization",snmpcpu.get("lastvalue"));
        }else{
            // 没有默认为0
            snmpdevice.put("CPUUtilization",0);
        }
        if(snmpmemory.get("lastvalue")!=null){
            // 获得最新的值
            snmpdevice.put("MemoryUtilization",snmpmemory.get("lastvalue"));
        }else{
            //没有默认为0
            snmpdevice.put("MemoryUtilization",0);
        }
        snmpdevice.put("lastclock",latesttime);
        // 格式化数据 将时间戳改为年月日 时分秒
        DateUtils.formatListDate(snmpdevice,"lastclock");
        return snmpdevice;
    }

//    @Override
//    public List<Map<String, Object>> getHostList(Integer pageNo, Integer pageSize, String status) {
//        return null;
//    }

    // return null 还不如不 return /(ㄒoㄒ)/~~
    public List<Map<String, Object>> getHostList_new(Integer pageNo, Integer pageSize, String status) {
        return null;
    }
    /**
     *
     * @description: 获取被监控设备列表(正确判断可用性和状态间关系)
     * @param:
     * @return:
     * @author:
     * @time:
     */
    @Override
    public List<Map<String, Object>> getHostListLogic(Integer pageNo, Integer pageSize, String status, Integer hostType) {
        // 分页获得设备信息
        List<Map<String,Object>> resultlist = getHostList_new(pageNo,pageSize,status,hostType);
//        System.out.println("````" + resultlist);
//        resultlist = getPagingData(resultlist, pageNo, pageSize);
        List<Map<String, Object>> result = new ArrayList<>();
        // 重新封装数据
        for (Map<String, Object> maps : resultlist) {
            // 将每次遍历的maps封装到最终结果resultMap
            Map<String, Object> resultMap = new HashMap<>();
            String hostid = (String) maps.get("hostid");
            Object item = maps.get("item");
            resultMap.put("hostid",hostid);
            resultMap.put("item",item);
            String hostname = (String) maps.get("hostname");
            resultMap.put("hostname",hostname);
            String status1 = maps.get("status").toString();
            String ip = maps.get("ip").toString();
            resultMap.put("ip",ip);
            String available = maps.get("avail").toString();
            resultMap.put("avail",available);
            Object inventory = maps.get("inventory");
            resultMap.put("inventory",inventory);
            if("未知".equals(available)){
                available = "不可用";
            }
            // 只取最后三个字符用于判定可用状态
            available = available.substring(available.length()-3,available.length());
            if ("已禁用".equals(status1)){
                resultMap.put("available","不可用");
            }else if("已启用".equals(status1)){
                if("不可用".equals(available)){
                    resultMap.put("available","不可用");
                }else{
                    resultMap.put("available","可用");
                }
            }
            result.add(resultMap);
        }
//        System.out.println("Logic：" + result);
        return result;
    }


    /**
     *
     * @description: 分类获取被监控设备列表(可用/不可用筛选)
     * @param:
     * @return:
     * @author:
     * @time:
     */
    @Override
    public List<Map<String, Object>> getHostListAvailClassify(Integer pageNo, Integer pageSize, String status,Integer hostType) {
        // 中转，逻辑分类获得可用状态的设备
        List<Map<String,Object>> resultlist = getHostListLogic(pageNo,pageSize,status,hostType);
//        resultlist = getPagingData(resultlist, pageNo, pageSize);
//        List<Map<String, Object>> result = new ArrayList<>();
//        if ("".equals(status))
//            return resultlist;
//        for (Map<String, Object> maps : resultlist) {
//            String available = (String) maps.get("available");
//            if (status.equals(available)){
//                result.add(maps);
//            }
//        }
//        return result;
        return resultlist;
    }
    /**
     *
     * @description: 获取被监控设备 可用性 列表(包括可用和无状态)
     * @param:
     * @return:
     * @author:
     * @time:
     */
    @Override
    public List<Map<String, Object>> getAvailableHostList(Integer pageNo, Integer pageSize, String status) {
        final String token = APIUtils.getToken();
//        获得主机详细信息列表
        List<Map<String, Object>> hostList = getAvailableHostList();
//        根据状态筛选
        String status_num = "";
        if (status.equals("已启用")) {
            status_num = "0";
        }
        else if (status.equals("已禁用")) {
            status_num = "1";
        }
        List<Map<String, Object>> hostList_temp = new ArrayList<>();
        if (status != null && status != ""){
            for (Map<String, Object> map : hostList) {
                if (map.get("status").toString().equals(status_num)){
                    hostList_temp.add(map);
                }
            }
            hostList = hostList_temp;
        }
//        分页
        hostList = getPagingData(hostList, pageNo, pageSize);
//        组装主机id数组 ids
        final List<String> hostIds = new ArrayList<>();
        final List<String> hosts = new ArrayList<>();

        for (Map<String, Object> maps : hostList) {
            hostIds.add((String) maps.get("hostid"));
            hosts.add((String) maps.get("host"));
        }
//        获取主机接口列表
        List<Map<String, Object>> hostInterfaceList = getHostInterfaceListByHostIds(hostIds);
        List<Map<String, Object>> result = new ArrayList<>();
        int offset = 0;
        for (int i = 0; i < hostList.size(); i++){
            // 通过主机hostid获得设备状态
            List<Map<String, Object>> state = new HostServiceImpl().getHostStatusById(token, hosts.get(i));
            Map<String, Object> resultMap = new HashMap<>();
            // 此为判断当前为什么类型
            /**                  0          1               2
             * available       未知       服务器可用      服务器不可用
             * ipmi_available  未知       单向网闸可用    单向网闸不可用
             * jmx_available   未知       防火墙可用      防火墙不可用
             * snmp_available  未知       交换机可用      交换机不可用
             */
            if ("1".equals(state.get(0).get("available"))){
                resultMap.put("avail","ZBX");
            }else if("2".equals(state.get(0).get("available"))){
                continue;
            }else {
                if ("1".equals(state.get(0).get("ipmi_available"))){
                    resultMap.put("avail","IPMI");
                }else if("2".equals(state.get(0).get("ipmi_available"))) {
                    continue;
                }else {
                    if ("1".equals(state.get(0).get("jmx_available"))){
                        resultMap.put("avail","JMX");
                    }else if("2".equals(state.get(0).get("jmx_available"))) {
                        continue;
                    }else {
                        if ("1".equals(state.get(0).get("snmp_available"))){
                            resultMap.put("avail","SNMP");
                        }else if("2".equals(state.get(0).get("snmp_available"))) {
                            continue;
                        }else{
                            continue;
                        }
                    }
                }
            }
            // 封装ip port
            if (resultMap.get("ip") == null) {
                resultMap.put("ip", hostInterfaceList.get(i + offset).get("ip") + ":" + hostInterfaceList.get(i + offset).get("port"));
            }else {
                offset++;
                continue;
            }
            // 封装状态，转为中文
            resultMap.put("hostname", hostList.get(i).get("name"));
            if (hostList.get(i).get("status").toString().equals("0"))
                resultMap.put("status", "已启用");
            else
                resultMap.put("status", "已禁用");
            resultMap.put("hostid", hostList.get(i).get("hostid"));

//            resultMap.put("available", );
            result.add(resultMap);
        }
        return result;
    }

    /**
     *
     * @description: 获取被监控设备 可用性 列表(包括可用和无状态)
     * @param:
     * @return:
     * @author:
     * @time:
     */
    @Override
    public List<Map<String, Object>> getAvailableHostList(){
        List<Map<String, Object>> result = new ArrayList<>();
        // 获得所有设备
        List<Map<String, Object>> hostList = new DemoServiceImpl().getAllOnlineHost();
        /**                  0          1               2
         * available       未知       服务器可用      服务器不可用
         * ipmi_available  未知       单向网闸可用    单向网闸不可用
         * jmx_available   未知       防火墙可用      防火墙不可用
         * snmp_available  未知       交换机可用      交换机不可用
         */
        for (Map<String, Object> maps : hostList) {
            if ("1".equals(maps.get("available"))){
                result.add(maps);
            }else if("2".equals(maps.get("available"))){
                continue;
            }else {
                if ("1".equals(maps.get("ipmi_available"))){
                    result.add(maps);
                }else if("2".equals(maps.get("ipmi_available"))) {
                    continue;
                }else {
                    if ("1".equals(maps.get("jmx_available"))){
                        result.add(maps);
                    }else if("2".equals(maps.get("jmx_available"))) {
                        continue;
                    }else {
                        if ("1".equals(maps.get("snmp_available"))){
                            result.add(maps);
                        }else if("2".equals(maps.get("snmp_available"))) {
                            continue;
                        }else{
                            continue;
                        }
                    }
                }
            }
        }
        return result;
    }

    /**
     *
     * @description: 获取被监控设备 不可用性 列表
     * @param:
     * @return:
     * @author:
     * @time:
     */
    @Override
    public List<Map<String, Object>> getUnAvailableHostList(Integer pageNo, Integer pageSize, String status) {
        final String token = APIUtils.getToken();
//        获得主机详细信息列表
        List<Map<String, Object>> hostList = getUnAvailableHostList();
//        根据状态筛选
        String status_num = "";
        if (status.equals("已启用")) {
            status_num = "0";
        }
        else if (status.equals("已禁用")) {
            status_num = "1";
        }
        List<Map<String, Object>> hostList_temp = new ArrayList<>();
        if (status != null && status != ""){
            for (Map<String, Object> map : hostList) {
                if (map.get("status").toString().equals(status_num)){
                    hostList_temp.add(map);
                }
            }
            hostList = hostList_temp;
        }
//        分页
        hostList = getPagingData(hostList, pageNo, pageSize);
//        组装主机id数组 ids
        final List<String> hostIds = new ArrayList<>();
        final List<String> hosts = new ArrayList<>();

        for (Map<String, Object> maps : hostList) {
            hostIds.add((String) maps.get("hostid"));
            hosts.add((String) maps.get("host"));
        }
//        获取主机接口列表
        List<Map<String, Object>> hostInterfaceList = getHostInterfaceListByHostIds(hostIds);
        List<Map<String, Object>> result = new ArrayList<>();
        int offset = 0;
        /**                  0          1               2
         * available       未知       服务器可用      服务器不可用
         * ipmi_available  未知       单向网闸可用    单向网闸不可用
         * jmx_available   未知       防火墙可用      防火墙不可用
         * snmp_available  未知       交换机可用      交换机不可用
         */
        for (int i = 0; i < hostList.size(); i++){
            List<Map<String, Object>> state = new HostServiceImpl().getHostStatusById(token, hosts.get(i));
            Map<String, Object> resultMap = new HashMap<>();
            if ("1".equals(state.get(0).get("available"))){
                continue;
            }else if("2".equals(state.get(0).get("available"))){
                resultMap.put("avail","ZBX不可用");
            }else {
                if ("1".equals(state.get(0).get("ipmi_available"))){
                    continue;
                }else if("2".equals(state.get(0).get("ipmi_available"))) {
                    resultMap.put("avail", "IPMI不可用");
                }else {
                    if ("1".equals(state.get(0).get("jmx_available"))){
                        continue;
                    }else if("2".equals(state.get(0).get("jmx_available"))) {
                        resultMap.put("avail", "JMX不可用");
                    }else {
                        if ("1".equals(state.get(0).get("snmp_available"))){
                            continue;
                        }else if("2".equals(state.get(0).get("snmp_available"))) {
                            resultMap.put("avail", "SNMP不可用");
                        }else{
                            resultMap.put("avail","未知");
                        }
                    }
                }
            }
            // 封装ip+port
            if (resultMap.get("ip") == null) {
                resultMap.put("ip", hostInterfaceList.get(i + offset).get("ip") + ":" + hostInterfaceList.get(i + offset).get("port"));
            }else {
                offset++;
                continue;
            }
            resultMap.put("hostname", hostList.get(i).get("name"));
            // 将状态转为中文
            if (hostList.get(i).get("status").toString().equals("0"))
                resultMap.put("status", "已启用");
            else
                resultMap.put("status", "已禁用");
            resultMap.put("hostid", hostList.get(i).get("hostid"));

//            resultMap.put("available", );

            result.add(resultMap);
        }
        return result;
    }

    /**
     *
     * @description: 获取被监控设备 不可用性 列表
     * @param:
     * @return:
     * @author:
     * @time:
     */
    @Override
    public List<Map<String, Object>> getUnAvailableHostList() {
        List<Map<String, Object>> result = new ArrayList<>();
        List<Map<String, Object>> hostList = new DemoServiceImpl().getAllOnlineHost();
        /**                  0          1               2
         * available       未知       服务器可用      服务器不可用
         * ipmi_available  未知       单向网闸可用    单向网闸不可用
         * jmx_available   未知       防火墙可用      防火墙不可用
         * snmp_available  未知       交换机可用      交换机不可用
         */
        for (Map<String, Object> maps : hostList) {
            if ("1".equals(maps.get("available"))){
                continue;
            }else if("2".equals(maps.get("available"))){
                result.add(maps);
            }else {
                if ("1".equals(maps.get("ipmi_available"))){
                    continue;
                }else if("2".equals(maps.get("ipmi_available"))) {
                    result.add(maps);
                }else {
                    if ("1".equals(maps.get("jmx_available"))){
                        continue;
                    }else if("2".equals(maps.get("jmx_available"))) {
                        result.add(maps);
                    }else {
                        if ("1".equals(maps.get("snmp_available"))){
                            continue;
                        }else if("2".equals(maps.get("snmp_available"))) {
                            result.add(maps);
                        }else{
                            result.add(maps);
                        }
                    }
                }
            }
        }
        return result;
    }

    /**
     *
     * @description: 根据主机ids获取主机接口信息
     * @param:
     * @return:
     * @author:
     * @time:
     */
    public List<Map<String, Object>> getHostInterfaceListByHostIds(List<String> hostIds){
        // 获得token指令
        final String token = APIUtils.getToken();
        ArrayList<String> inter_ip_port = new ArrayList<>();
        inter_ip_port.add("ip");
        inter_ip_port.add("port");
        Map<String, Object> paramsMap = new HashMap<String, Object>(){{
            put("jsonrpc", "2.0");
            put("method", "hostinterface.get");
            put("id", 1);
            put("auth", token);
            put("params", new HashMap<String, Object>(){{
                put("output",inter_ip_port);
                put("hostids",hostIds);
            }});
        }};
//        获取主机接口信息列表
        Map<String, Object> hostInterfaceMap = APIUtils.sendRequest(JSON.toJSONString(paramsMap, SerializerFeature.WriteMapNullValue));
        return  (List<Map<String, Object>>)hostInterfaceMap.get("result");
    }

    /**
     *
     * @description: 获取可用性状态被监控设备总数
     * @param:
     * @return:
     * @author:
     * @time:
     * @param
     */
    public Integer getHostCountByAvail(){
        List<Map<String, Object>> hostList = new DemoServiceImpl().getAllOnlineHost();
        int count = 0;
        // 统计所有设备不同可用状态的数量
        for (Map<String, Object> map : hostList) {
            if ("1".equals(map.get("available").toString()))  //服务器
                count++;
            else if("1".equals(map.get("ipmi_available").toString())) //单项网闸
                count ++;
            else if("1".equals(map.get("jmx_available").toString()))  // 防火墙
                count ++;
            else if("1".equals(map.get("snmp_available").toString()))  //网络设备
                count ++;
            else
                continue;
        }
        return count;
    }

    /**
     *
     * @description: 获取不可用性状态被监控设备总数
     * @param:
     * @return:
     * @author:
     * @time:
     * @param
     */
    public Integer getHostCountByUnAvail(){
        List<Map<String, Object>> hostList = new DemoServiceImpl().getAllOnlineHost();
        int count = 0;
        // 获得不可用设备，这里应该时非1才对，不用了这段代码，如果有需要可以加个！
        for (Map<String, Object> map : hostList) {
            if ("1".equals(map.get("available").toString()))
                continue;
            else if("1".equals(map.get("ipmi_available").toString()))
                continue;
            else if("1".equals(map.get("jmx_available").toString()))
                continue;
            else if("1".equals(map.get("snmp_available").toString()))
                continue;
            else
                count++;
        }
        return count;
    }
    /**
     *
     * @description: 获取被监控设备总数
     * @param:
     * @return:
     * @author:
     * @time:
     * @param
     */
    public Integer getHostCountByType(Integer hostType) {
        List<Map<String, Object>> hostList = new DemoServiceImpl().getAllOnlineHost();
        List<Map<String, Object>> ZBXHostList = new ArrayList<>();
        List<Map<String, Object>> SNMPHostList = new ArrayList<>();
        for (Map<String, Object> map : hostList) {
            if(map.get("available").toString().equals("0"))
                SNMPHostList.add(map);
            else
                ZBXHostList.add(map);
        }
        if (hostType == 0)
            return ZBXHostList.size(); // 返回服务器个数
        else
            return SNMPHostList.size(); // 返回网络设备个数
    }
    /**
     * @description: 根据主机类型进行可用/不可用分类
     *
     **/

    @Override
    public Integer getHostCountByTypeAndStatus(Integer hostType, String status) {
        List<Map<String, Object>> hostList = new DemoServiceImpl().getAllOnlineHost();
        Integer count1 = 0; //不可用总数
        Integer count2 = 0; //可用总数
        Integer count = 0;  //总数
        for (Map<String,Object> map:hostList){
            String ZBXavailable = map.get("available").toString();
            String SNMPavailable = map.get("snmp_available").toString();

            if (hostType == 0 && SNMPavailable.equals("0")) {
                if("0".equals(ZBXavailable) || "2".equals(ZBXavailable) )
                    count1++;
                else if ("1".equals(ZBXavailable) )
                    count2++;
                count++;
            }
            else if (hostType == 1 && ZBXavailable.equals("0")){
                if ("0".equals(SNMPavailable) || "2".equals(SNMPavailable) )
                    count1++;
                else if ("1".equals(SNMPavailable) )
                    count2++;
            }

        }

        if ("不可用".equals(status))
            return count1;  // 不可用设备数量
        else if ("可用".equals(status))
            return count2;  // 可用设备数量
        return getHostCountByType(hostType);
    }

    /**
     *
     * @description: 获取被监控设备总数
     * @param:
     * @return:
     * @author:
     * @time:
     * @param
     */
    public Integer getHostCountByStatus(String status) {
        List<Map<String, Object>> hostList = new DemoServiceImpl().getAllOnlineHost();
        int count = 0;
        String status_num = "";
        // 翻译类型
        if ("已启用".equals(status)) {
            status_num = "0";
        }
        else if ("已禁用".equals(status)) {
            status_num = "1";
        }
        if (status != null && status != "") {
            for (Map<String, Object> map : hostList) {
                if (status_num.equals(map.get("status").toString()))
                    count++;
            }
            return count;
        }else {
            return hostList.size();
        }
    }

    // 临时方法，获得所有设备的数量
    public Integer getHostCount() {
        List<Map<String, Object>> hostList = new DemoServiceImpl().getAllOnlineHost();
        return hostList.size();
    }

    /**
     *
     * @description: 根据hostId获取监控指标
     * @param:
     * @return:
     * @author:
     * @time:
     */
    @Override
    public List<Map<String, Object>> getItemByHostId(final String hostId) {
        final String token = APIUtils.getToken();
        Map<String, Object> paramsMap = new HashMap<String, Object>(){{
            put("jsonrpc", "2.0");
            put("method", "item.get");
            put("id", 1);
            put("auth", token);
            put("params", new HashMap<String, Object>(){{
                put("output", "extend");
                put("hostids", hostId);
            }});
        }};
        // 结果序列化
        Map<String, Object> responseMap = APIUtils.sendRequest(JSON.toJSONString(paramsMap, SerializerFeature.WriteMapNullValue));
        List<Map<String, Object>> resultList = (List<Map<String, Object>>)responseMap.get("result");
        return resultList;
    }


    /**
     * @description: 根据hostId获取应用集
     * @param:
     * @return:
     * @author
     * @date:
     */
    @Override
    public List<Map<String, Object>> getApplicationByHostId(final String hostId) {
        final String token = APIUtils.getToken();
        Map<String, Object> applicationsMap = new HashMap<String, Object>(){{
            put("jsonrpc", "2.0");
            put("method", "application.get");
            put("id", 1);
            put("auth", token);
            put("params", new HashMap<String, Object>(){{
                put("output", "extend");
                put("hostids", hostId);
                put("sortfield", "name");//根据名称排序
            }});
        }};

        //结果序列化
        Map<String, Object> responseMap = APIUtils.sendRequest(JSON.toJSONString(applicationsMap, SerializerFeature.WriteMapNullValue));
        List<Map<String, Object>> resultList = (List<Map<String, Object>>) responseMap.get("result");

        return resultList;
    }

    /**
     * @description:  通过应用集查询监控项
     * @param:
     * @return:
     * @author
     * @date:
     */
    @Override
    public List<Map<String, Object>> getItemByApplication(final List<Map<String, Object>> applicationList, final String hostId){
        final String token = APIUtils.getToken();
        List<Map<String, Object>> resultList = new ArrayList<>();
        final List<String> itemnames = new ArrayList<>();
        // 定义输出
        final String[] outputs = new String[]{"name", "lastvalue", "units"};

        itemnames.add("Context switches per second");
        itemnames.add("Available memory in %");
        itemnames.add("Load average (1m avg)");
        itemnames.add("Memory utilization");
        itemnames.add("Number of running processes");
        itemnames.add("Space utilization");
        itemnames.add("Used space");
        itemnames.add("Interface eth0: Bits received ");
        itemnames.add("Interface eth0: Bits sent ");

        for(int i = 0; i < applicationList.size(); i++){
            final String applicationId = (String) applicationList.get(i).get("applicationid");

            Map<String, Object> itemMap = new HashMap<String, Object>(){{
                put("jsonrpc", "2.0");
                put("method", "item.get");
                put("id", 1);
                put("auth", token);
                put("params", new HashMap<String, Object>(){{
                    put("output", outputs);
                    put("hostids", hostId);
                    put("applicationids", applicationId);
                    // 过滤条件
                    put("filter",new HashMap<String,Object>(){{
                        put("name",itemnames);
                    }});
                }});
            }};
            // 格式化时间
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Map<String, Object> responseMap = APIUtils.sendRequest(JSON.toJSONString(itemMap, SerializerFeature.WriteMapNullValue));
            List temp = (List)responseMap.get("result");
            if (!temp.isEmpty()){
                responseMap.put("applicationname", applicationList.get(i).get("name"));
                responseMap.put("applicationid", applicationId);
                responseMap.put("updateTime", sdf.format(new Date()));
                resultList.add(responseMap);
            }
        }
        return resultList;
    }

    /**
     * @description:  根据itemId获取历史数据
     * @param:
     * @return:
     * @author
     * @date:
     */
    @Override
    public List<Map<String, Object>> getNetOfSnmpByName(final String hostId, final String itemName) {
        // 获得token令牌
        final String token = APIUtils.getToken();
        final String[] outputs = new String[]{"itemid", "name"};
        Map<String, Object> value_typeMap = new HashMap<String, Object>(){{
            put("jsonrpc", "2.0");
            put("method", "item.get");
            put("id", 1);
            put("auth", token);
            put("params", new HashMap<String, Object>(){{
                put("output", outputs);
                put("hostids", hostId);
                // 通过监控项名称查找
                put("search", new HashMap<String, Object>(){{
                    put("name", itemName);
                }});
            }});
        }};
        //结果序列化
        Map<String, Object> ItemMap = APIUtils.sendRequest(JSON.toJSONString(value_typeMap, SerializerFeature.WriteMapNullValue));
        List<Map<String, Object>> ItemList = (List<Map<String, Object>>) ItemMap.get("result");

        //获取数据类型
        //筛选
        List<String> newItemIdList = new ArrayList<String>();
        String itemid = null;
        String name = null;
        List<Map<String, Object>> returnList = new ArrayList<Map<String, Object>>();

        for (int i = 0; i < ItemList.size(); i++){
            itemid = (String) ItemList.get(i).get("itemid");
            name = (String) ItemList.get(i).get("name");

            // 是否包含关键字(比特）
            if(name.contains("Bits received") || name.contains("Bits sent")){
                newItemIdList.add(itemid);
                String finalItemid = itemid;
                String finalName = name;
                // 封装监控项
                Map<String, Object> items = new HashMap<String, Object>(){{
                    put("itemid", finalItemid);
                    put("name", finalName);
                    put("data", null);
                }};
                returnList.add(items);
            }
        }

        // 挑选监控项*10个数量
        final Integer limit = newItemIdList.size() * 10;
        Map<String, Object> historyDataOfNet = new HashMap<String, Object>(){{
            put("jsonrpc", "2.0");
            put("method", "history.get");
            put("id", 1);
            put("auth", token);
            put("params", new HashMap<String, Object>(){{
                put("output", "extend");
                put("history",3);
                put("sortfield","clock");  // 通过clock排序
                put("sortorder", "DESC");  //降序
                put("itemids",newItemIdList);
                put("limit", limit);
            }});
        }};
        // 结果序列化
        Map<String, Object> responseOfHistoryDataMap = APIUtils.sendRequest(JSON.toJSONString(historyDataOfNet, SerializerFeature.WriteMapNullValue));
        List<Map<String, Object>> resultList = (List<Map<String, Object>>) responseOfHistoryDataMap.get("result");
//      调整格式
        for (Map<String, Object> temp : returnList){
            List<Map<String, Object>> datas = new ArrayList<Map<String, Object>>();
            for(Map<String, Object> historyData : resultList) {
                if (temp.get("itemid").equals(historyData.get("itemid"))){
                    // 时间戳转化为年月日 时分秒
                    DateUtils.formatListDate(historyData, "clock");
                    datas.add(new HashMap<String, Object>(){{
                        put("clock", historyData.get("clock"));
                        put("value", historyData.get("value"));
                    }});
                }
            }
            // 封装数据
            temp.put("data", datas);
        }

        return returnList;
    }


//    /**
//     * @description 获取高负载设备
//     * @author zengcong
//     * @param sortfield
//     * @return
//     */
//    @Override
//    public List<Map<String, Object>> getHighLoadHostList(String sortfield){
//        List<Map<String, Object>> filteResultList = getImportItem();
//        List<Map<String,Object>> sortresultList = sortList(filteResultList,sortfield);
//        DecimalFormat df = new DecimalFormat("0.00");
//        List<String> tempkey = new ArrayList<>();
//        tempkey.add("hostname");
//        tempkey.add("ip");
//        tempkey.add("hostinterface");
//        tempkey.add("cpufreq");
//        List<String> liststrings = new ArrayList<>();
//        liststrings.add("DiskWriterate");
//        liststrings.add("DiskReadrate");
//        liststrings.add("receivebit");
//        liststrings.add("sentbit");
//        liststrings.add("specification");
//        liststrings.add("hostid");
//        liststrings.add("clock");
//        for (Map<String, Object> map : sortresultList) {
//            Iterator<Map.Entry<String, Object>> it = map.entrySet().iterator();
//            while (it.hasNext()){
//                Map.Entry<String, Object> entry = it.next();
//                String itemkey = entry.getKey();
//                if(tempkey.contains(itemkey)) continue;
//                else{
//                    if ("CPUUtilization".equals(itemkey)) {
//                        String cpu_util = df.format(Double.valueOf(map.get("CPUUtilization").toString()));
//                        entry.setValue(cpu_util);
//                    }else{
//                        if("MemoryUtilization".equals(itemkey)) {
//                            String memory_util = df.format(Double.valueOf(map.get("MemoryUtilization").toString()));
//                            entry.setValue(memory_util);
//                        }else if(!liststrings.contains(itemkey)){
//                            // 对磁盘的读写进行格式修改
//                            if("DiskReadrateWindows".equals(itemkey) || "DiskWriterateWindows".equals(itemkey)){
//                                String tempStr = map.get(itemkey).toString();
//                                String itemvalue = df.format(Double.valueOf(tempStr.substring(0,tempStr.length() - 3)));
//                                entry.setValue(itemvalue);
//                            }else if("systemName".equals(itemkey)){
//                                String itemvalue = map.get(itemkey).toString();
//                                entry.setValue(itemvalue);
//                            }else {
//                                String itemvalue = df.format(Double.valueOf(map.get(itemkey).toString()));
//                                entry.setValue(itemvalue);
//                            }
//                        }
//                    }
//                }
//            }
//        }
//        if (sortresultList.size() > 10) {
//            sortresultList = sortresultList.subList(0, 10);
//        }else {
//            sortresultList = sortresultList.subList(0, sortresultList.size());
//        }
//        return sortresultList;
//    }

    /*
     * 获取cpu利用率，内存利用率，磁盘利用率，网络IO速率，磁盘读写速率
     * */
//    public List<Map<String,Object>> getImportItem(){
//        final String token = APIUtils.getToken();
//        List<String> output = new ArrayList<>();
//        output.add("name");
//        output.add("lastvalue");
//        output.add("key_");
//        output.add("hostid");
//        String[] itemProperty = new String[]{"key_","lastvalue","lastclock","name"};
//        String[] interfaceProperty = new String[]{"ip","port"};
//        Map<String,Object> paramsMap = new HashMap<String, Object>(){{
//            put("jsonrpc", "2.0");
//            put("method", "host.get");
//            put("id", 1);
//            put("auth", token);
//            put("params", new HashMap<String, Object>(){{
//                put("output", output);
//                put("selectItems", itemProperty);
//                put("selectInterfaces",interfaceProperty);
//                put("filter", new HashMap<String,Object>(){{
//                    put("status",0);
//                    put("monitored_hosts", true);
//                    put("available",1);
//                }});
////                put("search",new HashMap<String,Object>(){{
////                    put("snmp_available",2);
////                    put("available",1);
////                }});
//            }});
//        }};
//        Map<String, Object> responseMap = APIUtils.sendRequest(JSON.toJSONString(paramsMap, SerializerFeature.WriteMapNullValue));
//        List<Map<String, Object>> resultList = (List<Map<String, Object>>) responseMap.get("result");
//        List<Map<String,Object>> filteResultList = filterItemdata(resultList);
//        System.out.println("~~~~" + filteResultList);
//        return filteResultList;
//    }
    /**
     * @description 根据接口获取主机的重要监控项
     * @author zengcong
     */
    public Map<String,Object> getImportantItemByHostid(String hostid,List<Map<String, Object>> hostItems){
        Map<String,Object> res = new HashMap<>();
        // 指定监控项键值，通过键值查询
        String[] items = new String[]{"MemoryUtilization","CPUUtilization","DiskUtilization","DiskWriterate","DiskReadrate","receivebit","sentbit","specification","clock","DiskWriterateWindows","DiskReadrateWindows","systemName"};
        for(int i=0;i<hostItems.size();i++){
            Map<String,Object> hostItem = hostItems.get(i);
            // 判断是否相等
            if(hostid.equals(hostItem.get("hostid"))){
                for (int j=0;j< items.length;j++){
                    String key = items[j];
                    // 判断是否包含键值
                    if(!hostItem.containsKey(key)){
                        res.put(key,"");
                    }
                    else{
                        String value = hostItem.get(key).toString();
                        res.put(key,value);
                    }
                }
                return res;
            }
        }
        return null;
    }
    /**
     * @description 对list<MAP>数据排序
     * @author zengcong
     * @param data
     * @param sortfield
     * @return
     */

    public List<Map<String,Object>> sortList(List<Map<String,Object>> data ,String sortfield){
        Collections.sort(
                data, new Comparator<Map<String, Object>>() {
                    //排序，通过sortfield字段排序
                    public int compare(Map<String, Object> m1, Map<String, Object> m2) {
                        Double item1value = Double.valueOf(m1.get(sortfield).toString());
                        Double item2value = Double.valueOf(m2.get(sortfield).toString());
                        return item2value.compareTo(item1value);
                    }
                }
        );
        return data;
    }

    /**
     * @author zengcong
     * 过滤监控项数据
     * @return
     */

    public List<Map<String,Object>> filterItemdata(List<Map<String, Object>>  resultList){
        List<Map<String,Object>> filterResultList = new ArrayList<>();
        // 白能力结果
        for(int i=0; i< resultList.size(); i++){
            Map<String, Object> data = resultList.get(i);
            Map<String,Object> finaldata = new HashMap<>();
            finaldata.put("hostname",data.get("name"));
            finaldata.put("hostid",data.get("hostid"));
            // 获得ip和port
            List<Map<String, Object>> ipAndport = (List<Map<String,Object>>)resultList.get(i).get("interfaces");
            String ip = ipAndport.get(0).get("ip").toString();
            String port = ipAndport.get(0).get("port").toString();
            String hostinterface = ip + ":" + port;
            finaldata.put("hostinterface",hostinterface);
            finaldata.put("ip",ip);
            // 获得监控项items
            List<Map<String, Object>> items = (List<Map<String,Object>>)resultList.get(i).get("items");
            long finalTime = 0;
            String device = null;
            long totalSpace = 0L;
            long usedSpace = 0l;
            for(int j = 0;j<items.size();j++){
                // 获得键值
                String itemkey = items.get(j).get("key_").toString();
                // 获得监控项名称
                String itemname = items.get(j).get("name").toString();
                // 获得监控项最后的时间
                long itemTime = Long.parseLong(items.get(j).get("lastclock").toString());
                // 判断是否包含键值
                if("vm.memory.utilization".equals(itemkey)|| "vm.memory.util".equals(itemkey)){
                    String memoryvalue = items.get(j).get("lastvalue").toString();
                    // 将数据封装到最终的Map中
                    finaldata.put("MemoryUtilization",memoryvalue);
                    if (itemTime > finalTime){
                        finalTime = itemTime;
                    }
                }
                else if("system.cpu.util".equals(itemkey)){ //同理，不用的键值而已
                    String cpuvalue = items.get(j).get("lastvalue").toString();
                    finaldata.put("CPUUtilization",cpuvalue);
                    if (itemTime > finalTime){
                        finalTime = itemTime;
                    }
                }
                else if(itemkey.contains("vfs.dev.write")){ //同上
                    Double digits = Double.valueOf(items.get(j).get("lastvalue").toString());
                    String diskWriterate = new Formatter().format("%.2f",digits).toString()+"sps";
                    finaldata.put("DiskWriterate",diskWriterate);
                    if (itemTime > finalTime){
                        finalTime = itemTime;
                    }
                }
                else if(itemkey.contains("vfs.dev.read")){ //同上
                    Double digits = Double.valueOf(items.get(j).get("lastvalue").toString());
                    String diskReadrate = new Formatter().format("%.2f",digits).toString()+"sps";
                    finaldata.put("DiskReadrate",diskReadrate);
                    if (itemTime > finalTime){
                        finalTime = itemTime;
                    }
                }
                else if(itemkey.contains("perf_counter[\\2\\18]")){ //同上
                    Double digits = Double.valueOf(items.get(j).get("lastvalue").toString());
                    String diskWriterate = new Formatter().format("%.2f",digits).toString()+"sps";
                    finaldata.put("DiskWriterateWindows",diskWriterate);
                    if (itemTime > finalTime){
                        finalTime = itemTime;
                    }
                }
                else if(itemkey.contains("perf_counter[\\2\\16]")){ //同上
                    Double digits = Double.valueOf(items.get(j).get("lastvalue").toString());
                    String diskReadrate = new Formatter().format("%.2f",digits).toString()+"sps";
                    finaldata.put("DiskReadrateWindows",diskReadrate);
                    if (itemTime > finalTime){
                        finalTime = itemTime;
                    }
                }
                else if("net.if.in[\"eth0\"]".equals(itemkey)){ //同上
                    String recieveeth0 = items.get(j).get("lastvalue").toString();
                    Double recieveeth0digits = Double.valueOf(recieveeth0)/1000;
                    String recieveeth0format = new Formatter().format("%.2f", recieveeth0digits).toString()+"Kbps";
                    finaldata.put("receivebit",recieveeth0format);
                    if (itemTime > finalTime){
                        finalTime = itemTime;
                    }
                }
                else if("net.if.out[\"eth0\"]".equals(itemkey)){ //同上
                    String senteth0 = items.get(j).get("lastvalue").toString();
                    Double senteth0digits = Double.valueOf(senteth0)/1000;
                    String senteth0format = new Formatter().format("%.2f", senteth0digits).toString()+"Kbps";
                    finaldata.put("sentbit",senteth0format);
                    if (itemTime > finalTime){
                        finalTime = itemTime;
                    }
                }
                else if("system.hw.cpu[0,curfreq]".equals(itemkey)){ //同上
                    String cpufreq = items.get(j).get("lastvalue").toString();
                    Double cpufreqdigits = Double.valueOf(cpufreq)/1000000000;
                    finaldata.put("cpufreq",cpufreqdigits.toString());
                    if (itemTime > finalTime){
                        finalTime = itemTime;
                    }
                }
                else if("vfs.fs.size[/,total]".equals(itemkey)){ //同时
                    String totalmemory = items.get(j).get("lastvalue").toString();
                    Double totalmemorydigits = Double.valueOf(totalmemory)/(1024*1024*1024);
                    String totoalmemorydata = String.valueOf(totalmemorydigits.intValue());
                    finaldata.put("totalmemory",totoalmemorydata);
                    if (itemTime > finalTime){
                        finalTime = itemTime;
                    }
                }else if("system.uname".equals(itemkey)){ //同上
                    String systemName = items.get(j).get("lastvalue").toString();
                    finaldata.put("systemName",systemName);
                    if (itemTime > finalTime){
                        finalTime = itemTime;
                    }
                }
                // 添加磁盘利用率
//                Map<String,Object> map = new HashMap<>();

                // 判断磁盘的全部空间
                if(itemname.contains("Total space"))
                {
                    totalSpace+=Long.parseLong(items.get(j).get("lastvalue").toString());
                }
                else if(itemname.contains("Used space")) // 判断磁盘的使用空间
                {
                    usedSpace+=Long.parseLong(items.get(j).get("lastvalue").toString());
                }


//                if("System boot time".equals(items.get(j).get("name").toString()))
//                {
//                    DateUtils.formatListDate(stringObjectMap,"lastvalue");
//                }
//                if (itemTime > finalTime){
//                    finalTime = itemTime;
//                }
//                map.put("totalSpace",totalSpace);
//                map.put("usedSpace",usedSpace);

                if(!finaldata.containsKey("MemoryUtilization")){  //同上
                    finaldata.put("MemoryUtilization",0);
                }
                if(!finaldata.containsKey("CPUUtilization")){ //同上，不想解释了
                    finaldata.put("CPUUtilization",0);
                }
            }
//            System.out.println("usedSpace:" + usedSpace);
//            System.out.println("totalSpace:" + totalSpace);
            finaldata.put("DiskUtilization", ((double)usedSpace/(double)totalSpace)*100);
//            System.out.println("DiskUtilization" + (double)usedSpace/(double)totalSpace);
            //时间格式转化
            if (finalTime != 0){
                Map<String, Object> timeMap = new HashMap<>();
                timeMap.put("clock", finalTime);
                DateUtils.formatListDate(timeMap, "clock");
                finaldata.put("clock", timeMap.get("clock").toString());
            }else {
                finaldata.put("clock", "暂无时间数据");
            }

            if(finaldata.get("cpufreq")!=null && finaldata.get("totalmemory") !=null){
                String specification = finaldata.get("cpufreq").toString() + "GHz-" + finaldata.get("totalmemory").toString()+ "GB";
                finaldata.put("specification", specification);
            }else{
                finaldata.put("specification", "获取规格失败");
            }
            filterResultList.add(finaldata);
        }
//        for(int i =0;i<filterResultList.size();i++){
//            System.out.println("---"+filterResultList.get(i));
//        }
        return filterResultList;
    }

    /**
     * @description: 获取zabbix类型设备的流量数据
     * @param:
     * @return:
     * @author
     * @date:
     */
    @Override
    public List<Map<String, Object>> getNetData(final String hostId) {
        final String token = APIUtils.getToken();
        //获取与流量相关的监控项id
        final String[] outputs = new String[]{"itemid", "name"};
        Map<String, Object> netData = new HashMap<String, Object>(){{
            put("jsonrpc", "2.0");
            put("method", "item.get");
            put("id", 1);
            put("auth", token);
            put("params", new HashMap<String, Object>(){{
                put("output", outputs);
                put("hostids",hostId);
                put("search", new HashMap<String, Object>(){{
                    put("key_", "net.if");
                    put("type", "0");
                    put("value_type", "3");
                }});
            }});
        }};
        // 结果序列化
        Map<String, Object> responseOfNetData = APIUtils.sendRequest(JSON.toJSONString(netData, SerializerFeature.WriteMapNullValue));
        List<Map<String, Object>> netList = (List<Map<String, Object>>) responseOfNetData.get("result");
//      筛选出:Bits received 和 Bits sent两种流量数据
        List<String> itemList = new ArrayList<String>();
        String itemid = null;
        String name = null;
        List<Map<String, Object>> returnList = new ArrayList<Map<String, Object>>();
        for (int i = 0; i < netList.size(); i++){
            // 获得键值
            itemid = (String) netList.get(i).get("itemid");
            // 获得监控项名称
            name = (String) netList.get(i).get("name");
            // 判断是否包含键值
            if(name.contains("Bits received") || name.contains("Bits sent")){
                itemList.add(itemid);
                String finalItemid = itemid;
                String finalName = name;
                Map<String, Object> items = new HashMap<String, Object>(){{
                    put("itemid", finalItemid);
                    put("name", finalName);
                    put("data", null);
                }};
                returnList.add(items);
            }
        }
//      通过监控项id查出历史数据
        final Integer limit = itemList.size() * 10;
        ArrayList<String> his_details = new ArrayList<>();
        his_details.add("itemid");
        his_details.add("clock");
        his_details.add("value");
        // 获得历史网络数据
        Map<String, Object> historyDataOfNet = new HashMap<String, Object>(){{
            put("jsonrpc", "2.0");
            put("method", "history.get");
            put("id", 1);
            put("auth", token);
            put("params", new HashMap<String, Object>(){{
                put("output", his_details);  //定义输出
                put("history",3);
                put("sortfield","clock");   // 按照clock排序
                put("sortorder", "DESC");   // 降序
                put("itemids",itemList);
                put("limit", limit);
            }});
        }};
        //结果序列化
        Map<String, Object> responseOfHistoryDataMap = APIUtils.sendRequest(JSON.toJSONString(historyDataOfNet, SerializerFeature.WriteMapNullValue));
        List<Map<String, Object>> resultList = (List<Map<String, Object>>) responseOfHistoryDataMap.get("result");
//      调整格式
        for (Map<String, Object> temp : returnList){
            List<Map<String, Object>> datas = new ArrayList<Map<String, Object>>();
            for(Map<String, Object> historyData : resultList) {
                if (temp.get("itemid").equals(historyData.get("itemid"))){
                    // 时间戳转为年月日时分秒
                    DateUtils.formatListDate(historyData, "clock");
                    datas.add(new HashMap<String, Object>(){{
                        put("clock", historyData.get("clock"));
                        put("value", historyData.get("value"));
                    }});
                }
            }
            temp.put("data", datas);
        }

        return returnList;
    }

    /**
     * @description: 获取snmp设备的流量相关的接口
     * @param:
     * @return:
     * @author
     * @date:
     */
    @Override
    public List<Map<String, Object>> getInterfaceOfSnmpByHostId(final String hostId) {
        // 获得token令牌
        final String token = APIUtils.getToken();
        final String[] outputs = new String[]{"itemid", "name"};
        Map<String, Object> applicationsMap = new HashMap<String, Object>(){{
            put("jsonrpc", "2.0");
            put("method", "item.get");
            put("id", 1);
            put("auth", token);
            put("params", new HashMap<String, Object>(){{
                put("output", outputs); // 定义输出
                put("hostids", hostId); // 指定设备hostid
                put("search", new HashMap<String, Object>(){{
                    put("name", "Bits sent");  //查找网络数据
                }});
            }});
        }};
        // 结果序列化
        Map<String, Object> responseMap = APIUtils.sendRequest(JSON.toJSONString(applicationsMap, SerializerFeature.WriteMapNullValue));
        List<Map<String, Object>> resultList = (List<Map<String, Object>>) responseMap.get("result");
        //切分name字段用于确定snmp具体监控项名
        resultList = TextUtils.spiltInterfaceName(resultList);
        return resultList;
    }

    //查询日志监控id
    @Override
    public List<Map<String, String>> getLogItemId(String hostId) {
        final String token = APIUtils.getToken();
        List<Map<String, String>> logsNameAndId = new ArrayList<>();
        // 查询设备类型，添加对应的日志键值以供查询
        int sysType = hostService.checkSystemType(hostId);
        // 定义输出
        final String[] output = new String[]{"itemid", "state", "status","name"};
        Map<String, Object> paramsMap = new HashMap<String, Object>(){{
            put("jsonrpc", "2.0");
            put("method", "item.get");
            put("id", 1);
            put("auth", token);
            put("params", new HashMap<String, Object>(){{
                put("output", output);
                put("hostids", hostId);
                put("search", new HashMap<String, Object>(){{
                    if (sysType == 0){ // 定义键值，查找符合键值的日志
                       put("key_", "eventlog");
                    }else if (sysType == 1){
                       put("key_", "log");
                    }else if (sysType == 2){
                                            // 暂未配置
                    }
                    put("type", "7");               // 7为日志
                    put("value_type", "2");
                }});
            }});
        }};
        // 结果序列化
        Map<String, Object> responseMap = APIUtils.sendRequest(JSON.toJSONString(paramsMap, SerializerFeature.WriteMapNullValue));
        List<Map<String, Object>> resultList = (List<Map<String, Object>>)responseMap.get("result");
        if (resultList.size() != 0){
            for (Map<String, Object> map : resultList) {
                if (Integer.parseInt(map.get("state").toString()) == 0 && Integer.parseInt(map.get("status").toString()) == 0){
                    Map tempMap = new HashMap();
                    tempMap.put("name",map.get("name").toString());
                    tempMap.put("id",map.get("itemid").toString());
                   logsNameAndId.add(tempMap);
                }
            }
            return logsNameAndId;
        }else{
            return null;
        }

        /*
         * 实际上可能存在很多日志监控项（比如配置多了的情况下，甚至每个日志监控项对应的日志文件不同）
         * 但是暂时只返回了一个日志（后续根据需求改进）
         * */
        //for (Map<String, Object> map : resultList) {
        //    if (Integer.parseInt(map.get("state").toString()) == 0 && Integer.parseInt(map.get("status").toString()) == 0){
        //        return map.get("itemid").toString();
        //    }
        //}
    }

    //获取日志历史数据
    @Override
    public List<Map<String, Object>> getLogHistoryDataByItemId(String itemId, String startDate, String endDate, String currentPage) {
        // 获得token令牌
        final String token = APIUtils.getToken();
        String[] output = {"clock", "value"};
        Map<String, Object> paramsMap= new HashMap<String, Object>(){{
            put("jsonrpc", "2.0");
            put("method", "history.get");   //获得历史数据
            put("id", 1);
            put("auth", token);
            put("params", new HashMap<String, Object>(){{
                put("output", output);
                put("history",2);
                put("sortfield","clock");   //根据clock排序
                put("sortorder", "DESC");   //降序
                put("itemids",itemId);
            }});
        }};

        // 结果序列化
        Map<String, Object> responseMap = APIUtils.sendRequest(JSON.toJSONString(paramsMap, SerializerFeature.WriteMapNullValue));
        if (responseMap == null){
            return  null;
        }else {
            List<Map<String, Object>> historyList = (List<Map<String, Object>>) responseMap.get("result");
            //调整格式
            for (Map<String, Object> oneResult : historyList) {
                DateUtils.formatListDate(oneResult, "clock");
            }
            //截取指定时间范围
            List<Map<String, Object>> specifiedTimeData = DateUtils.getSpecifiedTimeDataDesc(historyList, startDate, endDate);
            int total = specifiedTimeData.size();
            Map<String, Object> totalMap = new HashMap<>();
            totalMap.put("total",total);
            //分页
            List<Map<String, Object>> resultList = PageUtils.getDataListByCurPage(specifiedTimeData, currentPage, "10");
            resultList.add(totalMap);
            //System.out.println(resultList.size());

            return resultList;
        }

    }


    /**
     *
     * @description: 获取指定主机占用资源前5的进程
     * @param:
     * @return:
     * @author:
     * @time:
     */
    @Override
    public List<Map<String, Object>> getCpuUsageByProcess(String hostIp, String hostId) {
        final String token = APIUtils.getToken();

//        String ip = "172.16.239.3";
        String ip = hostIp;
        Host host = hostMapper.getUserInfoById(hostId);
        String out = "";
        try {   //向指定ip发送指令，要保证用户名和密码正确，此为设备登录用户名和密码
            out = ActionUtils.sendCommandToHost(ip, host.getUserName(), host.getPassword(), "ps auxw|head -1; ps auxw|sort -rn -k3|head -5");
        }catch (Exception e){
            System.out.println(e.getMessage());     //我不知道为什么，我写的？毫无印象，
        }
        String finalOut = out;
        Map<String, Object> resMap = new HashMap<String, Object>() {{
            put("result", finalOut);
        }};
//        System.out.println(out);
        String[] strings = out.split("\n");
        List<Map<String, Object>> result = new ArrayList<>();
        for (int i = 1; i < strings.length; i++) {
            List<String> list = new ArrayList<>();
            Map<String, Object> map = new HashMap<>();
            // 任意空白字符作为切割pattern
            String[] split = strings[i].split("\\s+");
            list.add(split[2]);
            list.add(split[3]);
            map.put("cpuUtilization", split[2]);    //cpu利用率
            map.put("memoryUtilization", split[3]); // 内存利用率
            if (split.length > 11){
                String command = "";
                for (int j = 10; j < split.length; j++){
                    command += split[j];
                }
                map.put("processName", command);    //进程名称
            }else {
                map.put("processName", split[10]);  //进程名称
            }
            result.add(map);
        }
        return result;
    }
//    @Override
//    public List<Map<String, Object>> getCpuUsageByProcess(String hostIp, String userName, String password) {
//        final String token = APIUtils.getToken();
//        String ip = "172.16.239.3";
////        String ip = hostIp;
//        String out = ActionUtils.sendCommandToHost(ip, userName, password, "ps auxw|head -1; ps auxw|sort -rn -k3|head -5");
//        Map<String, Object> resMap = new HashMap<String, Object>() {{
//            put("result", out);
//        }};
//        System.out.println(out);
//        String[] strings = out.split("\n");
//        List<Map<String, Object>> result = new ArrayList<>();
//        for (int i = 1; i < strings.length; i++) {
//            List<String> list = new ArrayList<>();
//            Map<String, Object> map = new HashMap<>();
//            String[] split = strings[i].split("\\s+");
//            list.add(split[2]);
//            list.add(split[3]);
//            map.put("cpuUtilization", split[2]);
//            map.put("memoryUtilization", split[3]);
//            if (split.length > 11){
//                String command = "";
//                for (int j = 10; j < split.length; j++){
//                    command += split[j];
//                }
//                map.put("processName", command);
//            }else {
//                map.put("processName", split[10]);
//            }
//            result.add(map);
//        }
//        return result;
//    }


    /**
     * @description: 根据监控项名获取监控项
     *  （硬件信息）
     */
    @Override
    public List<Map<String, Object>> getItemByName(String[] itemsName, String hostId) {
        final String token = APIUtils.getToken();
        //定义输出
        final String[] outputs = new String[]{"name", "lastvalue", "units"};
        List<Map<String, Object>> itemInf = new ArrayList<>();

        Map<String, Object> nameAndValue = new HashMap<>();
        nameAndValue.put("numberOfCPUs", 0);    //cpu数量
        nameAndValue.put("totalMemory", 0);     // 内存大小

        for (final String itemName : itemsName) {
            Map<String, Object> paramsMap = new HashMap<String, Object>() {{
                put("jsonrpc", "2.0");
                put("method", "item.get");
                put("id", 1);
                put("auth", token);
                put("params", new HashMap<String, Object>() {{
                    put("output", outputs);
                    put("hostids", hostId);
                    put("search", new HashMap<String, Object>() {{
                        put("name", itemName);  //查找指定监控项名称的监控项
                    }});
                }});
            }};
            // 结果序列化
            Map<String, Object> responseMap = APIUtils.sendRequest(JSON.toJSONString(paramsMap, SerializerFeature.WriteMapNullValue));
            List<Map<String, Object>> result = (List<Map<String, Object>>) responseMap.get("result");
            if (result.size() != 0) {
                // 监控项名称
                String name = (String) result.get(0).get("name");
                // 监控项的值
                double lastValue = Double.parseDouble(result.get(0).get("lastvalue").toString());
                // 监控项单位
                String units = (String) result.get(0).get("units");
                //单位转换
                if (units.equals("B") && lastValue != 0) {
                    lastValue = lastValue / Math.pow(1024, 3);
                    units = "GB";
                }
                if (name.equals("Number of CPUs") || name.equals("Number of cores") ) {
                    name = "numberOfCPUs";
                } else {
                    name = "totalMemory";
                }
                // 保留两位小数
                nameAndValue.put(name, String.format("%.2f", lastValue) + "" + units);
                itemInf.add(nameAndValue);
            }
        }
        return itemInf;
    }

    /**
     * 优化后的高负载页面
     * @param sortfield
     * @return
     */
    public List<Map<String, Object>> getHighLoadHostList_new(String sortfield) {

        String token = APIUtils.getToken();
        List<Map<String,Object>> result_sort = new ArrayList<>();

        List<Map<String,Object>> hostids = new ArrayList<>();
        hostids = hostService.get_all_host_imporant(token);
        List<Map<String,Object>> hostids_snmp = hostService.get_all_snmp_host_imporant(token);

        JSONArray JSON_hostids = JSON.parseArray(String.valueOf(hostids));
        JSONArray JSON_snmp_hostids = JSON.parseArray(String.valueOf(hostids_snmp));
        // 隐去网络设备
        // JSONArray JSON_snmp_hostids = new JSONArray();

        Set<String> hostid_list = new HashSet<>();
        for (int i = 0; i < JSON_hostids.size(); i++) {
            JSONObject hostid = JSON.parseObject(JSON_hostids.getString(i));
            hostid_list.add(hostid.getString("hostid"));
        }
        for (int i = 0; i < JSON_snmp_hostids.size(); i++) {
            JSONObject hostid = JSON.parseObject(JSON_snmp_hostids.getString(i));
            hostid_list.add(hostid.getString("hostid"));
        }

        if (sortfield.equals("CPUUtilization")){    // 判断是否为cpu利用率
            List<Map<String, Object>> filteResultList = itemService.get_cup_item(token, new ArrayList<>(hostid_list));
            // 转换为JSONArray
            JSONArray jsonArray = JSONArray.parseArray(String.valueOf(filteResultList));

            List<Map<String,Object>> result_list = new ArrayList<>();

            // 遍历jsons数组对象，
            for (int i = 0; i < jsonArray.size(); i++) {
                Map<String,Object> result_map = new HashMap<>();
                // JSONArray 转为 JSONObject对象
                JSONObject cur_object = JSON.parseObject(jsonArray.getString(i));
                Map<String,Object> cur_map = DateUtils.JsonToMap(cur_object);
                result_map.put("hostid",cur_map.get("hostid"));
                String cur_key = (String) cur_map.get("key_");
//            if (cur_key.contains("vm.memory.util")){
//                result_map.put("memory_value",cur_map.get("lastvalue"));
//            }
                if (cur_key.contains("system.cpu.util")){   // 是否包含该键值
                    result_map.put("cpu_value",cur_map.get("lastvalue"));
                }
                result_list.add(result_map);
            }
//        System.out.println(result_list);
            MonitorService monitorService = new MonitorServiceImpl();
            // 测试类型
            List<Map<String,Object>> sortresultList;
            // 按照cpu排序
            sortresultList= monitorService.sortList(result_list,"cpu_value");
            int count = sortresultList.size();
            if (count < 10) {
                sortresultList = sortresultList.subList(0,count);
            }else{
                sortresultList = sortresultList.subList(0,10);
            }
//        System.out.println(sortresultList);
            for (int i = 0; i < sortresultList.size(); i++) {
                String hostid = (String) sortresultList.get(i).get("hostid");
//                System.out.println(hostid);
                // 通过设备hostid获得cpu和内存信息
                List<Map<String, Object>> rec_item = itemService.get_cup_and_mem_item_byid(hostid, token);
                //通过设备hostid获得设备详情
                List<Map<String, Object>> rec_host = hostService.get_details_by_hostid(token,hostid);
                JSONArray jsonArray_item = JSONArray.parseArray(String.valueOf(rec_item));
                JSONArray jsonArray_host = JSONArray.parseArray(String.valueOf(rec_host));
//                System.out.println(jsonArray_item);
//            System.out.println(jsonArray_host);
                // 遍历jsons数组对象，
                Map<String,Object> result_map = new HashMap<>();
                for (int j = 0; j < jsonArray_item.size(); j++) {
                    JSONObject cur_item = JSON.parseObject(jsonArray_item.getString(j));
                    Map<String,Object> cur_item_map = DateUtils.JsonToMap(cur_item);
                    String key = (String) cur_item_map.get("key_");
                    if(key.contains("system.cpu.util")){
                        result_map.put("cpu_value",cur_item_map.get("lastvalue"));  //封装cpu的值
                    }
                    if(key.contains("vm.memory.util")){
                        result_map.put("mem_value",cur_item_map.get("lastvalue"));  //封装内存的值
                    }
                }
                for (int k = 0; k < jsonArray_host.size(); k++) {
                    // 重新封装数据
                    JSONObject cur_host = JSON.parseObject(jsonArray_host.getString(k));
                    Map<String,Object> cur_host_map = DateUtils.JsonToMap(cur_host);
                    result_map.put("hostid",cur_host_map.get("hostid"));
                    result_map.put("hostname",cur_host_map.get("name"));
                    result_map.put("interfaces",cur_host_map.get("interfaces"));
                }
                result_sort.add(result_map);
            }
        }else{
            // 通过设备hostid（不止一个）获得监控项信息
            List<Map<String, Object>> filteResultList = itemService.get_mem_item(token,new ArrayList<>(hostid_list));
            // 转换为JSONArray
            JSONArray jsonArray = JSONArray.parseArray(String.valueOf(filteResultList));
            List<Map<String,Object>> result_list = new ArrayList<>();
            // 遍历jsons数组对象，
            for (int i = 0; i < jsonArray.size(); i++) {
                Map<String,Object> result_map = new HashMap<>();
                JSONObject cur_object = JSON.parseObject(jsonArray.getString(i));
                Map<String,Object> cur_map = DateUtils.JsonToMap(cur_object);
                result_map.put("hostid",cur_map.get("hostid"));
                String cur_key = (String) cur_map.get("key_");
                if (cur_key.contains("vm.memory.util")){
                    result_map.put("memory_value",cur_map.get("lastvalue"));    //获得内存的值
                }
//                if (cur_key.contains("system.cpu.util")){
//                    result_map.put("cpu_value",cur_map.get("lastvalue"));
//                }
                result_list.add(result_map);
            }
//        System.out.println(result_list);
            MonitorService monitorService = new MonitorServiceImpl();
            // 测试类型
            List<Map<String,Object>> sortresultList;
            // 按照cpu排序
            sortresultList= monitorService.sortList(result_list,"memory_value");
            int count = sortresultList.size();
            if (count < 10) {
                sortresultList = sortresultList.subList(0,count);
            }else{
                sortresultList = sortresultList.subList(0,10);
            }
//        System.out.println(sortresultList);
            for (int i = 0; i < sortresultList.size(); i++) {
                String hostid = (String) sortresultList.get(i).get("hostid");
                List<Map<String, Object>> rec_item = itemService.get_cup_and_mem_item_byid(hostid, token);
                List<Map<String, Object>> rec_host = hostService.get_details_by_hostid(token,hostid);
                JSONArray jsonArray_item = JSONArray.parseArray(String.valueOf(rec_item));
                JSONArray jsonArray_host = JSONArray.parseArray(String.valueOf(rec_host));
//                System.out.println("jsonArray_item:" + jsonArray_item);
//                System.out.println("jsonArray_host:" + jsonArray_host);
                // 遍历jsons数组对象，
                Map<String,Object> result_map = new HashMap<>();
                for (int j = 0; j < jsonArray_item.size(); j++) {
                    JSONObject cur_item = JSON.parseObject(jsonArray_item.getString(j));
                    Map<String,Object> cur_item_map = DateUtils.JsonToMap(cur_item);
                    String key = (String) cur_item_map.get("key_");     //通过键值封装数据
                    if(key.contains("system.cpu.util")){
                        result_map.put("cpu_value",cur_item_map.get("lastvalue"));
                    }
                    if(key.contains("vm.memory.util")){
                        result_map.put("mem_value",cur_item_map.get("lastvalue"));
                    }
                }
                for (int k = 0; k < jsonArray_host.size(); k++) {
                    JSONObject cur_host = JSON.parseObject(jsonArray_host.getString(k));
                    Map<String,Object> cur_host_map = DateUtils.JsonToMap(cur_host);
                    result_map.put("hostid",cur_host_map.get("hostid"));
                    result_map.put("hostname",cur_host_map.get("name"));
                    result_map.put("interfaces",cur_host_map.get("interfaces"));
                }
                result_sort.add(result_map);
            }
        }
        // 格式化的数据
        List<Map<String, Object>>filte_result_list = filterItemdata_highload_new(result_sort);
        // 格式化时间
        DecimalFormat df = new DecimalFormat("0.00");
        List<String> tempkey = new ArrayList<>();
        tempkey.add("hostname");
        tempkey.add("ip");
        List<String> liststrings = new ArrayList<>();
        liststrings.add("clock");
        for (Map<String, Object> map : filte_result_list) {
            Iterator<Map.Entry<String, Object>> it = map.entrySet().iterator();
            while (it.hasNext()){
                Map.Entry<String, Object> entry = it.next();
                String itemkey = entry.getKey();
                if(tempkey.contains(itemkey)) continue;
                else{
                    if ("CPUUtilization".equals(itemkey)) {
                        String cpu_util = df.format(Double.valueOf(map.get("CPUUtilization").toString()));  //格式化cpu利用率
                        entry.setValue(cpu_util);
                    }else{
                        if("MemoryUtilization".equals(itemkey)) {
                            String memory_util = df.format(Double.valueOf(map.get("MemoryUtilization").toString()));    //格式化内存利用率
                            entry.setValue(memory_util);
                        }
                    }
                }
            }
        }
        return filte_result_list;
    }

    /**
     * 数据过滤器
     * @param resultList
     * @return
     */
    public List<Map<String,Object>> filterItemdata_new(List<Map<String, Object>>  resultList) {
        List<Map<String,Object>> filterResultList = new ArrayList<>();
        // 重新封装数据
        for(int i=0; i< resultList.size(); i++){
            Map<String, Object> data = resultList.get(i);
            Map<String,Object> finaldata = new HashMap<>();
            finaldata.put("hostname",data.get("name"));
            finaldata.put("hostid",data.get("hostid"));
            finaldata.put("host",data.get("host"));
            // 获得ip和port
            List<Map<String, Object>> ipAndport = (List<Map<String,Object>>)resultList.get(i).get("interfaces");
            String ip = ipAndport.get(0).get("ip").toString();
            String port = ipAndport.get(0).get("port").toString();
            String hostinterface = ip + ":" + port;
            finaldata.put("hostinterface",hostinterface);
            finaldata.put("ip",ip);
            // 获得监控项详情
            List<Map<String, Object>> items = (List<Map<String,Object>>)resultList.get(i).get("item_details");
            long finalTime = 0;
            String device = null;
            long totalSpace = 0L;
            long usedSpace = 0l;
            for(int j = 0;j<items.size();j++){
                // 获得键值
                String itemkey = items.get(j).get("key_").toString();
                // 获得监控项名称
                String itemname = items.get(j).get("name").toString();
                long itemTime = Long.parseLong(items.get(j).get("lastclock").toString());
                if("vm.memory.utilization".equals(itemkey)|| "vm.memory.util".equals(itemkey)){     //键值是否包含内存
                    String memoryvalue = items.get(j).get("lastvalue").toString();
                    finaldata.put("MemoryUtilization",memoryvalue);
                    if (itemTime > finalTime){
                        finalTime = itemTime;
                    }
                }
                else if("system.cpu.util".equals(itemkey)){     //同理是否包含cpu
                    String cpuvalue = items.get(j).get("lastvalue").toString();
                    finaldata.put("CPUUtilization",cpuvalue);
                    if (itemTime > finalTime){
                        finalTime = itemTime;
                    }
                }
                else if(itemkey.contains("vfs.dev.write")){     //磁盘写速率
                    Double digits = Double.valueOf(items.get(j).get("lastvalue").toString());
                    String diskWriterate = new Formatter().format("%.2f",digits).toString()+"sps";
                    finaldata.put("DiskWriterate",diskWriterate);
                    if (itemTime > finalTime){
                        finalTime = itemTime;
                    }
                }
                else if(itemkey.contains("vfs.dev.read")){  //磁盘读速率
                    Double digits = Double.valueOf(items.get(j).get("lastvalue").toString());
                    String diskReadrate = new Formatter().format("%.2f",digits).toString()+"sps";
                    finaldata.put("DiskReadrate",diskReadrate);
                    if (itemTime > finalTime){
                        finalTime = itemTime;
                    }
                }
                else if(itemkey.contains("perf_counter[\\2\\18]")){     //磁盘使用率
                    Double digits = Double.valueOf(items.get(j).get("lastvalue").toString());
                    String diskWriterate = new Formatter().format("%.2f",digits).toString()+"sps";
                    finaldata.put("DiskWriterateWindows",diskWriterate);
                    if (itemTime > finalTime){
                        finalTime = itemTime;
                    }
                }
                else if(itemkey.contains("perf_counter[\\2\\16]")){     //磁盘使用率
                    Double digits = Double.valueOf(items.get(j).get("lastvalue").toString());
                    String diskReadrate = new Formatter().format("%.2f",digits).toString()+"sps";
                    finaldata.put("DiskReadrateWindows",diskReadrate);
                    if (itemTime > finalTime){
                        finalTime = itemTime;
                    }
                }
                else if("net.if.in[\"eth0\"]".equals(itemkey)){     //入网络 eth0接口
                    String recieveeth0 = items.get(j).get("lastvalue").toString();
                    Double recieveeth0digits = Double.valueOf(recieveeth0)/1000;
                    String recieveeth0format = new Formatter().format("%.2f", recieveeth0digits).toString()+"Kbps";
                    finaldata.put("receivebit",recieveeth0format);
                    if (itemTime > finalTime){
                        finalTime = itemTime;
                    }
                }
                else if("net.if.out[\"eth0\"]".equals(itemkey)){    //出网络 eth0接口
                    String senteth0 = items.get(j).get("lastvalue").toString();
                    Double senteth0digits = Double.valueOf(senteth0)/1000;
                    String senteth0format = new Formatter().format("%.2f", senteth0digits).toString()+"Kbps";
                    finaldata.put("sentbit",senteth0format);
                    if (itemTime > finalTime){
                        finalTime = itemTime;
                    }
                }
                else if("system.hw.cpu[0,curfreq]".equals(itemkey)){    //华为交换机cpu使用率
                    String cpufreq = items.get(j).get("lastvalue").toString();
                    Double cpufreqdigits = Double.valueOf(cpufreq)/1000000000;
                    finaldata.put("cpufreq",cpufreqdigits.toString());
                    if (itemTime > finalTime){
                        finalTime = itemTime;
                    }
                }
                else if("vfs.fs.size[/,total]".equals(itemkey)){    // 磁盘根目录的总大小
                    String totalmemory = items.get(j).get("lastvalue").toString();
                    Double totalmemorydigits = Double.valueOf(totalmemory)/(1024*1024*1024);
                    String totoalmemorydata = String.valueOf(totalmemorydigits.intValue());
                    finaldata.put("totalmemory",totoalmemorydata);
                    if (itemTime > finalTime){
                        finalTime = itemTime;
                    }
                }else if("system.uname".equals(itemkey)){   //系统名称
                    String systemName = items.get(j).get("lastvalue").toString();
                    finaldata.put("systemName",systemName);
                    if (itemTime > finalTime){
                        finalTime = itemTime;
                    }
                }
                // 添加磁盘利用率
//                Map<String,Object> map = new HashMap<>();

                if(itemname.contains("Total space"))       // 磁盘的全部空间
                {
                    totalSpace+=Long.parseLong(items.get(j).get("lastvalue").toString());
                }
                else if(itemname.contains("Used space"))    //磁盘的使用大小
                {
                    usedSpace+=Long.parseLong(items.get(j).get("lastvalue").toString());
                }


//                if("System boot time".equals(items.get(j).get("name").toString()))
//                {
//                    DateUtils.formatListDate(stringObjectMap,"lastvalue");
//                }
//                if (itemTime > finalTime){
//                    finalTime = itemTime;
//                }
//                map.put("totalSpace",totalSpace);
//                map.put("usedSpace",usedSpace);

                if(!finaldata.containsKey("MemoryUtilization")){
                    finaldata.put("MemoryUtilization",0);
                }
                if(!finaldata.containsKey("CPUUtilization")){
                    finaldata.put("CPUUtilization",0);
                }
            }
//            System.out.println("usedSpace:" + usedSpace);
//            System.out.println("totalSpace:" + totalSpace);
            finaldata.put("DiskUtilization", ((double)usedSpace/(double)totalSpace)*100);
//            System.out.println("DiskUtilization" + (double)usedSpace/(double)totalSpace);
            //时间格式转化
            if (finalTime != 0){
                Map<String, Object> timeMap = new HashMap<>();
                timeMap.put("clock", finalTime);
                DateUtils.formatListDate(timeMap, "clock");
                finaldata.put("clock", timeMap.get("clock").toString());
            }else {
                finaldata.put("clock", "暂无时间数据");
            }

            if(finaldata.get("cpufreq")!=null && finaldata.get("totalmemory") !=null){
                String specification = finaldata.get("cpufreq").toString() + "GHz-" + finaldata.get("totalmemory").toString()+ "GB";
                finaldata.put("specification", specification);
            }else{
                finaldata.put("specification", "获取规格失败");
            }
            filterResultList.add(finaldata);
        }
//        for(int i =0;i<filterResultList.size();i++){
//            System.out.println("---"+filterResultList.get(i));
//        }
        return filterResultList;
    }

    /**
     * 优化的获取主机列表
     * @param pageNo
     * @param pageSize
     * @param status
     * @param hostType
     * @return
     */
    public List<Map<String, Object>> getHostList_new(Integer pageNo, Integer pageSize, String status, Integer hostType) {
        final String token = APIUtils.getToken();
//        获得主机详细信息列表
        List<Map<String, Object>> hostList;
        if (hostType == 0) {
            hostList = new DemoServiceImpl().getAllOnlineHostid_agent();    //获得所有服务器
        }else {
            hostList = new DemoServiceImpl().getAllOnlineHostid_snmp();     //获得所有网络设备
        }
//        for (Map<String, Object> map : hostList) {
//            if(map.get("available").toString().equals("0"))
//                SNMPHostList.add(map);
//            else
//                ZBXHostList.add(map);
//        }
//        if (hostType == 0)
//            hostList = ZBXHostList;
//        else
//            hostList = SNMPHostList;


//        根据状态筛选
        String status_num = "";
        if ("可用".equals(status)) {
            status_num = "1";
        }
        else if ("不可用".equals(status)) {
            status_num = "2";
        }
//        System.out.println("状态：" + status);
        List<Map<String, Object>> hostList_temp = new ArrayList<>();
        // 存在状态，即不为空
        if (status != null && status != ""){
            // 主机类型为agent类型
            if (hostType == 0) {
                // 判断是否可用
                if (status.equals("可用")){
                    for (Map<String, Object> map : hostList) {
                        if (map.get("available").toString().equals("1")){   //可用
                            hostList_temp.add(map);
                        }
                    }
                }else{
                    for (Map<String, Object> map : hostList) {
                        if (map.get("available").toString().equals("2")){   //不可用
                            hostList_temp.add(map);
                        }
                    }
                }
            }else { //网络设备
                if (status.equals("可用")){
                    for (Map<String, Object> map : hostList) {
                        if (map.get("snmp_available").toString().equals("1")){
                            hostList_temp.add(map);
                        }
                    }
                }else{
                    for (Map<String, Object> map : hostList) {
                        if (map.get("snmp_available").toString().equals("2")){
                            hostList_temp.add(map);
                        }
                    }
                }

            }
        }else { //状态为空时，
            // 主机类型为agent类型
            if (hostType == 0) {
                for (Map<String, Object> map : hostList) {
                    if (map.get("available").toString().equals("1")){   //可用
                        hostList_temp.add(map);
                    }
                }
                for (Map<String, Object> map : hostList) {
                    if (map.get("available").toString().equals("2")){   //不可用
                        hostList_temp.add(map);
                    }
                }
            }else {
                for (Map<String, Object> map : hostList) {
                    if (map.get("snmp_available").toString().equals("1")){
                        hostList_temp.add(map);
                    }
                }
                for (Map<String, Object> map : hostList) {
                    if (map.get("snmp_available").toString().equals("2")){
                        hostList_temp.add(map);
                    }
                }
            }
        }
        hostList = hostList_temp;

//        分页
        hostList = getPagingData(hostList, pageNo, pageSize);
//        System.out.println("打印的hostlist:"+hostList);


//        组装主机id数组 ids
        final List<String> hostIds = new ArrayList<>();
        final List<String> hosts = new ArrayList<>();

//        for (Map<String, Object> maps : hostList) {
//            hostIds.add((String) maps.get("hostid"));
//            hosts.add((String) maps.get("host"));
//        }

//        获取主机接口列表
//        List<Map<String, Object>> hostInterfaceList = getHostInterfaceListByHostIds(hostIds);
        List<Map<String, Object>> result = new ArrayList<>();

        int offset = 0;
        List<String> hostid_list = new ArrayList<>();
//        HostService hostService = new HostServiceImpl();
        ItemService itemService = new ItemServiceImpl();
        List<Map<String,Object>> item_details;

        if (hostList.size() != 0) { //设备不为空
            for (int i = 0; i < hostList.size(); i++) {
                String id = (String) hostList.get(i).get("hostid");
                hostid_list.add(id);
            }
            for (int i = 0; i < hostid_list.size(); i++) {
                String hostid = hostid_list.get(i);
                Map cur_host = hostList.get(i);
                item_details = itemService.get_important_item_byid(hostid,token);       // 通过设备hostid获得监控项信息
//            System.out.println("获得的监控项：" + item_details);
                cur_host.put("item_details",item_details);
            }
            List<Map<String,Object>> filteResultList = filterItemdata_new(hostList);
            for (int i = 0; i < hostList.size(); i++){
//            List<Map<String, Object>> state = new HostServiceImpl().getHostStatusById(token, hosts.get(i));
//            Map<String, Object> inventory = new HostServiceImpl().getHostInventory(token, hostIds.get(i));
                List<Map<String, Object>> inter_details = (List<Map<String, Object>>) hostList.get(i).get("interfaces");    // 获得主机接口信息
//                JSONArray details = (JSONArray) hostList.get(i).get("inventory");
//                List<Map<String, Object>>  inven_details = (List<Map<String, Object>>) hostList.get(i).get("inventory");

//                List<Map> inven_details = JSON.parseArray(JSON.parseObject(String.valueOf(hostList.get(i))).getString("inventory"), Map.class);

                Map<String, Object> res = new HashMap<>();
                //判断类型
                if(hostList.get(i).get("inventory") instanceof JSONObject) {
                    JSONObject inven_details = JSON.parseObject(String.valueOf(hostList.get(i).get("inventory")));
                    res.put("notes",inven_details.getString("notes"));
                }
                if(hostList.get(i).get("inventory") instanceof JSONArray) {
                    JSONArray inven_details = JSON.parseArray(String.valueOf(hostList.get(i).get("inventory")));
                    if (inven_details.size() == 0) {
                        res.put("notes","");
                    }
                }
                Map<String, Object> resultMap = new HashMap<>();
                // 资产清单
                resultMap.put("inventory", res);
                //名称
                resultMap.put("hostname", hostList.get(i).get("host"));
                //接口
//            if (resultMap.get("ip") == null) {
//                resultMap.put("ip", hostInterfaceList.get(i + offset).get("ip") + ":" + hostInterfaceList.get(i + offset).get("port"));
//            }else {
//                offset++;
//                continue;
//            }
                resultMap.put("ip", inter_details.get(0).get("ip") + ":" + inter_details.get(0).get("port"));

                //可用性
//            System.out.println(state.get(0).get("available"));
//            System.out.println(state.get(0).get("ipmi_available"));
//            System.out.println(state.get(0).get("jmx_available"));
//            System.out.println(state.get(0).get("snmp_available"));
                // 判断类型
                if ("1".equals(hostList.get(i).get("available"))){
                    resultMap.put("avail","ZBX");
//                System.out.println("ZBX");
                }
                else if("2".equals(hostList.get(i).get("available"))){
                    resultMap.put("avail","ZBX不可用");
//                System.out.println("ZBX不可用");
                }else {
                    if ("1".equals(hostList.get(i).get("snmp_available"))){
                        resultMap.put("avail","SNMP");
//                            System.out.println("SNMP");
                    }else if("2".equals(hostList.get(i).get("snmp_available"))) {
                        resultMap.put("avail", "SNMP不可用");
//                            System.out.println("SNMP不可用");
                    }else{
                        resultMap.put("avail","未知");
//                            System.out.println("未知");
                    }
                }
                //状态
                if (hostList.get(i).get("status").toString().equals("0"))
                    resultMap.put("status", "已启用");
                else
                    resultMap.put("status", "已禁用");



                //其余新的添加
                Map<String, Object> item = null;
                if (hostType == 0){
                    //服务器
                    item = getImportantItemByHostid(hostList.get(i).get("hostid").toString(), filteResultList);
                }else{
                    //交换机
                    item = getSnmpCpuAndMemryByHostid(hostList.get(i).get("hostid").toString());
                }

                if (item != null){
                    resultMap.put("item", item);
                    resultMap.put("clock", item.get("clock"));
                }else {
                    resultMap.put("item", "暂未配置相关监控项");
                }
                //时间

                resultMap.put("hostid", hostList.get(i).get("hostid"));
//            System.out.println("最终的结果：" + resultMap);
                result.add(resultMap);
            }
        }
        return result;
    }

    /**
     * 数据过滤器
     * @param resultList
     * @return
     */
    public List<Map<String,Object>> filterItemdata_highload_new(List<Map<String, Object>>  resultList) {
        List<Map<String,Object>> filterResultList = new ArrayList<>();
//        JSONObject JSON_result = JSON.parseObject(String.valueOf(resultList));

        for(int i=0; i< resultList.size(); i++){
            Map<String,Object> finaldata = new HashMap<>();
            finaldata.put("hostname",resultList.get(i).get("hostname"));
            finaldata.put("hostid",resultList.get(i).get("hostid"));
            // 获得ip和端口号
            List<Map<String, Object>> ipAndport = (List<Map<String,Object>>)resultList.get(i).get("interfaces");
//            System.out.println("接口：" +ipAndport);
            String ip = ipAndport.get(0).get("ip").toString();
            String port = ipAndport.get(0).get("port").toString();
            String hostinterface = ip + ":" + port;
            finaldata.put("hostinterface",hostinterface);
            finaldata.put("ip",ip);
            // 获得内存值
            if (resultList.get(i).containsKey("mem_value")){
                String memoryvalue = resultList.get(i).get("mem_value").toString();
                finaldata.put("MemoryUtilization",memoryvalue);
            }

            if (resultList.get(i).containsKey("cpu_value")){    //获得cpu的值
                String cpuvalue = resultList.get(i).get("cpu_value").toString();
                finaldata.put("CPUUtilization",cpuvalue);
            }

//            if(!finaldata.containsKey("MemoryUtilization")){
//                finaldata.put("MemoryUtilization",0);
//            }
//            if(!finaldata.containsKey("CPUUtilization")){
//                finaldata.put("CPUUtilization",0);
//            }
            filterResultList.add(finaldata);
        }
        return filterResultList;
    }


    /**
     * 主页面的高负载请求
     * @param sortfield
     * @return
     */
    public List<Map<String, Object>> getHighLoadHostList_dashboard_new(String sortfield){
        String token = APIUtils.getToken();
        List<Map<String,Object>> result_sort = new ArrayList<>();
        List<Map<String,Object>> hostids = new ArrayList<>();
        hostids = hostService.get_all_host_imporant(token);
        List<Map<String,Object>> hostids_snmp = hostService.get_all_snmp_host_imporant(token);

        JSONArray JSON_hostids = JSON.parseArray(String.valueOf(hostids));
        JSONArray JSON_snmp_hostids = JSON.parseArray(String.valueOf(hostids_snmp));
        // 隐去网络设备
        // JSONArray JSON_snmp_hostids = new JSONArray();

        Set<String> hostid_list = new HashSet<>();
        for (int i = 0; i < JSON_hostids.size(); i++) {
            JSONObject hostid = JSON.parseObject(JSON_hostids.getString(i));
            hostid_list.add(hostid.getString("hostid"));
        }
        for (int i = 0; i < JSON_snmp_hostids.size(); i++) {
            JSONObject hostid = JSON.parseObject(JSON_snmp_hostids.getString(i));
            hostid_list.add(hostid.getString("hostid"));
        }

        if (sortfield.equals("CPUUtilization")){
            List<Map<String, Object>> filteResultList = itemService.get_cup_item(token,new ArrayList<>(hostid_list));     // 通过设备hostid（不止一个）获得cpu监控项信息
            // 转换为JSONArray
            JSONArray jsonArray = JSONArray.parseArray(String.valueOf(filteResultList));

            List<Map<String,Object>> result_list = new ArrayList<>();

            // 遍历jsons数组对象，
            for (int i = 0; i < jsonArray.size(); i++) {
                Map<String,Object> result_map = new HashMap<>();
                JSONObject cur_object = JSON.parseObject(jsonArray.getString(i));
                Map<String,Object> cur_map = DateUtils.JsonToMap(cur_object);
                result_map.put("hostid",cur_map.get("hostid"));
                String cur_key = (String) cur_map.get("key_");
                if (cur_key.contains("system.cpu.util")){   //判断是否包含cpu键值
                    result_map.put("cpu_value",cur_map.get("lastvalue"));
                }
                result_list.add(result_map);
            }
//        System.out.println(result_list);
            MonitorService monitorService = new MonitorServiceImpl();
            // 测试类型
            List<Map<String,Object>> sortresultList;
            // 按照cpu排序
            sortresultList= monitorService.sortList(result_list,"cpu_value");   //获得cpu的值
            int count = sortresultList.size();
            if (count < 5) {
                sortresultList = sortresultList.subList(0,count);   //只取0到count个
            }else{
                sortresultList = sortresultList.subList(0,5);
            }
//        System.out.println("cpuSortresultList:" + sortresultList);

            for (int i = 0; i < sortresultList.size(); i++) {
                String hostid = (String) sortresultList.get(i).get("hostid");

                List<Map<String, Object>> rec_host = hostService.get_details_by_hostid(token,hostid);   // 通过设备hostid获得设备详情
                JSONArray jsonArray_host = JSONArray.parseArray(String.valueOf(rec_host));

                // 遍历jsons数组对象，
                Map<String,Object> result_map = new HashMap<>();

                // 重新封装数据
                for (int k = 0; k < jsonArray_host.size(); k++) {
                    JSONObject cur_host = JSON.parseObject(jsonArray_host.getString(k));
                    Map<String,Object> cur_host_map = DateUtils.JsonToMap(cur_host);
                    result_map.put("hostid",cur_host_map.get("hostid"));
                    result_map.put("hostname",cur_host_map.get("name"));
                    result_map.put("interfaces",cur_host_map.get("interfaces"));
                }
                result_map.put("cpu_value",sortresultList.get(i).get("cpu_value"));
                result_sort.add(result_map);
            }
        }else{

            List<Map<String, Object>> filteResultList = itemService.get_mem_item(token,new ArrayList<>(hostid_list));
            // 转换为JSONArray
            JSONArray jsonArray = JSONArray.parseArray(String.valueOf(filteResultList));
            List<Map<String,Object>> result_list = new ArrayList<>();
            // 遍历jsons数组对象，
            for (int i = 0; i < jsonArray.size(); i++) {
                Map<String,Object> result_map = new HashMap<>();
                JSONObject cur_object = JSON.parseObject(jsonArray.getString(i));
                Map<String,Object> cur_map = DateUtils.JsonToMap(cur_object);
                result_map.put("hostid",cur_map.get("hostid"));
                String cur_key = (String) cur_map.get("key_");
                if (cur_key.contains("vm.memory.util")){
                    result_map.put("mem_value",cur_map.get("lastvalue"));
                }
                result_list.add(result_map);
            }
//        System.out.println(result_list);
            MonitorService monitorService = new MonitorServiceImpl();
            // 测试类型
            List<Map<String,Object>> sortresultList;
            // 按照cpu排序
            sortresultList= monitorService.sortList(result_list,"mem_value");
            int count = sortresultList.size();
            if (count < 5) {
                sortresultList = sortresultList.subList(0,count);
            }else{
                sortresultList = sortresultList.subList(0,5);
            }

//        System.out.println("memSortresultList:" + sortresultList);

            for (int i = 0; i < sortresultList.size(); i++) {
                String hostid = (String) sortresultList.get(i).get("hostid");

                List<Map<String, Object>> rec_host = hostService.get_details_by_hostid(token,hostid);
                JSONArray jsonArray_host = JSONArray.parseArray(String.valueOf(rec_host));

                // 遍历jsons数组对象，
                Map<String,Object> result_map = new HashMap<>();

                //重新封装数据
                for (int k = 0; k < jsonArray_host.size(); k++) {
                    JSONObject cur_host = JSON.parseObject(jsonArray_host.getString(k));
                    Map<String,Object> cur_host_map = DateUtils.JsonToMap(cur_host);
                    result_map.put("hostid",cur_host_map.get("hostid"));
                    result_map.put("hostname",cur_host_map.get("name"));
                    result_map.put("interfaces",cur_host_map.get("interfaces"));
                }
                result_map.put("mem_value",sortresultList.get(i).get("mem_value"));
                result_sort.add(result_map);
            }
        }
//        System.out.println("result_sort:" + result_sort);
        // 格式化的数据
        List<Map<String, Object>>filte_result_list = filterItemdata_highload_new(result_sort);
//        System.out.println("filte_result_list:" + filte_result_list);
        DecimalFormat df = new DecimalFormat("0.00");
        List<String> tempkey = new ArrayList<>();
        tempkey.add("hostname");
        tempkey.add("ip");
        List<String> liststrings = new ArrayList<>();
        liststrings.add("clock");
        for (Map<String, Object> map : filte_result_list) {
            Iterator<Map.Entry<String, Object>> it = map.entrySet().iterator();
            while (it.hasNext()){
                // 判断是哪一种键值
                Map.Entry<String, Object> entry = it.next();
                String itemkey = entry.getKey();
                if(tempkey.contains(itemkey)) continue;
                else{
                    if ("CPUUtilization".equals(itemkey)) {
                        String cpu_util = df.format(Double.valueOf(map.get("CPUUtilization").toString())); //格式化数据
                        entry.setValue(cpu_util);
                    }else{
                        if("MemoryUtilization".equals(itemkey)) {
                            String memory_util = df.format(Double.valueOf(map.get("MemoryUtilization").toString()));    // 格式化数据
                            entry.setValue(memory_util);
                        }
                    }
                }
            }
        }
        return filte_result_list;
    }

    /**
     * 数据过滤器
     * @param resultList
     * @return
     */
    public List<Map<String,Object>> filterItemdata_memory_new(List<Map<String, Object>>  resultList) {
        List<Map<String,Object>> filterResultList = new ArrayList<>();
//        JSONObject JSON_result = JSON.parseObject(String.valueOf(resultList));

        for(int i=0; i< resultList.size(); i++){
            Map<String,Object> finaldata = new HashMap<>();
            finaldata.put("hostname",resultList.get(i).get("hostname"));
            finaldata.put("hostid",resultList.get(i).get("hostid"));
            // 获得ip和端口号
            List<Map<String, Object>> ipAndport = (List<Map<String,Object>>)resultList.get(i).get("interfaces");
//            System.out.println("接口：" +ipAndport);
            String ip = ipAndport.get(0).get("ip").toString();
            String port = ipAndport.get(0).get("port").toString();
            String hostinterface = ip + ":" + port;
            finaldata.put("hostinterface",hostinterface);
            finaldata.put("ip",ip);
            String memoryvalue = resultList.get(i).get("mem_value").toString(); //获得内存的值
            finaldata.put("MemoryUtilization",memoryvalue);

//            if(!finaldata.containsKey("MemoryUtilization")){
//                finaldata.put("MemoryUtilization",0);
//            }
//            if(!finaldata.containsKey("CPUUtilization")){
//                finaldata.put("CPUUtilization",0);
//            }
            filterResultList.add(finaldata);
        }
        return filterResultList;
    }

    /**
     * 用于报表导出数据，后面新创的报表类，这个方法在这里不会被用到了
     * @param status
     * @param hostType
     * @return
     */
    @Override
    public Boolean ExportData(String status,Integer hostType) {
        final Integer count = getHostCountByTypeAndStatus(hostType,status);//获得该类型下的设备数量
        List<Map<String,Object>> resultList = getHostListAvailClassify(1,count,status,hostType);    //获得可用的设备列表
        // 新建一个excel
        HSSFWorkbook wb = new HSSFWorkbook();
        // 新建一个sheet
        HSSFSheet sheet = wb.createSheet();
        // 创建一行
        HSSFRow row = sheet.createRow(0);
        // 设定单元格的风格
        HSSFCellStyle style = wb.createCellStyle();
        style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
        // 创建当前行的单元格
        HSSFCell cell = row.createCell(0);
        // 设定单元格的值
        cell.setCellValue("设备名称");
        // 设定单元格宽度
        sheet.setColumnWidth(0,6000);
        // 设定单元格的份风格
        cell.setCellStyle(style);
        //原理同上
        cell = row.createCell(1);
        cell.setCellValue("CPU利用率");
        sheet.setColumnWidth(1,6000);
        cell.setCellStyle(style);
        cell = row.createCell(2);
        cell.setCellValue("内存利用率");
        sheet.setColumnWidth(2,6000);
        cell.setCellStyle(style);
        cell = row.createCell( 3);
        cell.setCellValue("磁盘利用率");
        sheet.setColumnWidth(3,6000);
        cell.setCellStyle(style);
        cell = row.createCell( 4);
        cell.setCellValue("磁盘IO速率(写/读)");
        sheet.setColumnWidth(4,6000);
        cell.setCellStyle(style);

        for (int i=0;i<resultList.size();i++){
            row = sheet.createRow(i+1);
            // 将数据写进单元格，分别获得哥哥数据
            row.createCell(0).setCellValue((String) resultList.get(i).get("hostname"));
            Map<String,Object> map = (Map<String, Object>) resultList.get(i).get("item");
            row.createCell(1).setCellValue((String)map.get("CPUUtilization"));
            row.createCell(2).setCellValue((String) map.get("MemoryUtilization"));
            row.createCell(3).setCellValue((String) map.get("DiskUtilization"));
            if (map.get("DiskWriterateWindows").toString()!="" && map.get("DiskReadrateWindows").toString()!="")
                row.createCell(4).setCellValue(map.get("DiskWriterateWindows")+"/"+map.get("DiskReadrateWindows"));
            else
                row.createCell(4).setCellValue(map.get("DiskWriterate")+"/"+map.get("DiskReadrate"));
        }
        try {
            //用字节流的方式写进excel文件中
            FileOutputStream fos = new FileOutputStream(new File("f:\\性能分析报表.xls"));
            // 写入
            wb.write(fos);
            // 关闭字节流
            fos.close();
        }catch (Exception e){
            e.getMessage();
        }
        return null;
    }


    /**
     * 获得监控项的信息
     * @param hostids
     * @param status
     * @param hostType
     * @return
     */
    @Override
    public List<Map<String, Object>> getItemDataInfo(String hostids,String status, Integer hostType) {
        // 获得token令牌
        final String token = APIUtils.getToken();
        List<Map<String, Object>> hostList=new ArrayList<>();
        List<Map<String, Object>> hostList_tmp;
        if (hostType == 0) {
            hostList_tmp = new DemoServiceImpl().getAllOnlineHostid_agent(); //获得所有服务器
        } else {
            hostList_tmp = new DemoServiceImpl().getAllOnlineHostid_snmp(); //获得所有网络设备
        }
        //重新封装数据
        for (int i =0;i<hostList_tmp.size();i++)
            if(hostids.equals(hostList_tmp.get(i).get("hostid"))){
                JSONObject obj = (JSONObject) hostList_tmp.get(i);
                Map<String,Object> resultMap_temp = new HashMap<>();
                resultMap_temp.put("interfaces",obj.get("interfaces"));
                if (obj.get("available")!=null)
                    resultMap_temp.put("available",obj.get("available"));
                else
                    resultMap_temp.put("snmp_available",obj.get("snmp_available"));
                resultMap_temp.put("host",obj.get("host"));
                resultMap_temp.put("hostid",obj.get("hostid"));
                resultMap_temp.put("inventory",obj.get("inventory"));
                resultMap_temp.put("status",obj.get("status"));
                hostList.add(resultMap_temp);
                break;
            }
        List<Map<String, Object>> hostList_temp = new ArrayList<>();
            // 状态不为空
        if (status != null && status != ""){
            // 主机类型为agent类型
            if (hostType == 0) {
                if (status.equals("可用")){
                    for (Map<String, Object> map : hostList) {
                        if (map.get("available").toString().equals("1")){   //可用
                            hostList_temp.add(map);
                        }
                    }
                }else{
                    for (Map<String, Object> map : hostList) {
                        if (map.get("available").toString().equals("2")){   //不可用
                            hostList_temp.add(map);
                        }
                    }
                }
            }else { //网络设备
                if (status.equals("可用")){
                    for (Map<String, Object> map : hostList) {
                        if (map.get("snmp_available").toString().equals("1")){ //同上
                            hostList_temp.add(map);
                        }
                    }
                }else{
                    for (Map<String, Object> map : hostList) {
                        if (map.get("snmp_available").toString().equals("2")){
                            hostList_temp.add(map);
                        }
                    }
                }
            }
        }else {
            // 主机类型为agent类型
            if (hostType == 0) {
                for (Map<String, Object> map : hostList) {
                    if (map.get("available").toString().equals("1")){
                        hostList_temp.add(map);
                    }
                }
                for (Map<String, Object> map : hostList) {
                    if (map.get("available").toString().equals("2")){
                        hostList_temp.add(map);
                    }
                }
            }else {
                for (Map<String, Object> map : hostList) {
                    if (map.get("snmp_available").toString().equals("1")){
                        hostList_temp.add(map);
                    }
                }
                for (Map<String, Object> map : hostList) {
                    if (map.get("snmp_available").toString().equals("2")){
                        hostList_temp.add(map);
                    }
                }
            }
        }
        hostList = hostList_temp;
        List<String> hostid_list = new ArrayList<>();
        ItemService itemService = new ItemServiceImpl();
        List<Map<String,Object>> item_details;
        if (hostList.size() != 0) {
            for (int i = 0; i < hostList.size(); i++) {
                String id = (String) hostList.get(i).get("hostid");
                hostid_list.add(id);
            }
            for (int i = 0; i < hostid_list.size(); i++) {
                String hostid = hostid_list.get(i);
                Map cur_host = hostList.get(i);
                if (hostType == 0)
                    item_details = itemService.get_important_item_byid(hostid, token);  // 通过设备hostid获得监控项信息
                else
                    item_details = itemService.get_snmp_item_id(hostid);
                cur_host.put("item_details", item_details);
            }
        }
        Map<String,Object> temp = new HashMap<>();
        temp.put("item_details",hostList.get(0).get("item_details"));
        List<Map<String, Object>> filteResultList = filterItemdata_new(hostList);   //过滤数据
        filteResultList.add(temp);
        return filteResultList;
    }


    /**
     * 通过监控项id获得趋势
     * @param itemid
     * @return
     */
    @Override
    public Map<String, Object> getTrendByItemid(String itemid) {
        // 获得token令牌
        final String token = APIUtils.getToken();
        Map<String, Object> paramsMap = new HashMap<String, Object>(){{
            put("jsonrpc", "2.0");
            put("method", "trend.get");
            put("id", 1);
            put("auth", token);
            put("params", new HashMap<String, Object>(){{
                put("output","extend"); //全部输出
                put("sortfield","clock");
                put("sortorder", "DESC");
                put("itemids",itemid);
            }});
        }};
//        获取主机接口信息列表
        Map<String, Object> resultMap = APIUtils.sendRequest(JSON.toJSONString(paramsMap, SerializerFeature.WriteMapNullValue));
        return  resultMap;
    }

    /**
     *
     * @param hostids
     * @param status
     * @param hostType
     * @return
     */
    @Override
    public Boolean getItem_by_DataInfo(String hostids, String status, Integer hostType) {
        List<Map<String,Object>> resultMap = getItemDataInfo(hostids,status,hostType);  //获得监控项数据信息
        int i = 0;
        String itemid;
        if (hostType == 0) {
            if (resultMap.get(0).get("DiskWriterate") != null) {    //判断磁盘写速率是否为空
                // 创建一个excel
                HSSFWorkbook wb = new HSSFWorkbook();
                // 创建一个sheet
                HSSFSheet sheet = wb.createSheet();
                // 创建一行
                HSSFRow row = sheet.createRow(0);
                // 设定行宽
                sheet.setColumnWidth(0, 6000);

                sheet.setColumnWidth(1, 6000);
                sheet.setColumnWidth(2, 6000);

                sheet.setColumnWidth(3, 6000);
                sheet.setColumnWidth(4, 6000);

                sheet.setColumnWidth(5, 6000);
                sheet.setColumnWidth(6, 6000);
                // 设定单元格的风格
                HSSFCellStyle style = wb.createCellStyle();
                // 居中对齐
                style.setAlignment(HSSFCellStyle.ALIGN_CENTER);


                HSSFCellStyle style_temp = wb.createCellStyle();
                // 设定颜色
                style_temp.setFillForegroundColor((short) 13);
                style_temp.setAlignment(HSSFCellStyle.ALIGN_CENTER);
                style_temp.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
                // 第0行
                HSSFCell cell = row.createCell(i);
                sheet.addMergedRegion(new CellRangeAddress(i, i, 1, 6));
                i++;
                cell.setCellValue("设备名称");
                cell.setCellStyle(style_temp);
                cell = row.createCell(1);
                cell.setCellValue(resultMap.get(0).get("host").toString());
                //第1行
                row = sheet.createRow(i);
                sheet.addMergedRegion(new CellRangeAddress(i, i, 0, 6));
                i++;
                //CPU利用率
                cell = row.createCell(0);
                cell.setCellValue("CPU利用率");
                cell.setCellStyle(style_temp);


                //第2行
                row = sheet.createRow(i);

                cell = row.createCell(0);
                cell.setCellValue("时间");
                cell.setCellStyle(style_temp);

                cell = row.createCell(1);
                cell.setCellValue("平均");
                cell.setCellStyle(style_temp);
                sheet.addMergedRegion(new CellRangeAddress(i, i, 1, 2));

                cell = row.createCell(3);
                cell.setCellValue("最大");
                cell.setCellStyle(style_temp);
                sheet.addMergedRegion(new CellRangeAddress(i, i, 3, 4));

                cell = row.createCell(5);
                cell.setCellValue("最小");
                cell.setCellStyle(style_temp);
                sheet.addMergedRegion(new CellRangeAddress(i, i, 5, 6));

                i++;
                //共i行
                itemid = ((JSONArray) getItemByHostidAndKey(hostids, "system.cpu.util").get("result")).getJSONObject(0).getString("itemid");    //通过键值获得监控项信息
                JSONArray array = (JSONArray) getTrendByItemid(itemid).get("result");
                array.sort(Comparator.comparing(obj -> {
                    Integer value = ((JSONObject) obj).getIntValue("clock");
                    return value;
                }).reversed());
                JSONObject arr_obj = (JSONObject) array.get(0);
                Long num = Long.valueOf(arr_obj.get("clock").toString());
                for (Iterator iterator = array.iterator(); iterator.hasNext(); ) {
                    JSONObject obj = (JSONObject) iterator.next();
                    if ((Long.valueOf(obj.get("clock").toString()) + 86400l) >= num) {      //最近一周
                        sheet.addMergedRegion(new CellRangeAddress(i, i, 1, 2));
                        sheet.addMergedRegion(new CellRangeAddress(i, i, 3, 4));
                        sheet.addMergedRegion(new CellRangeAddress(i, i, 5, 6));

                        row = sheet.createRow(i);
                        i++;
                        cell = row.createCell(0);
                        cell.setCellValue(DateUtils.SecondTimeStamp2Date(obj.get("clock").toString()));
                        cell.setCellStyle(style);

                        cell = row.createCell(1);
                        cell.setCellValue(obj.get("value_avg").toString());
                        cell.setCellStyle(style);

                        cell = row.createCell(3);
                        cell.setCellValue(obj.get("value_max").toString());
                        cell.setCellStyle(style);

                        cell = row.createCell(5);
                        cell.setCellValue(obj.get("value_min").toString());
                        cell.setCellStyle(style);
                    } else
                        break;
                }

                //内存利用率
                row = sheet.createRow(i);
                sheet.addMergedRegion(new CellRangeAddress(i, i, 0, 6));
                i++;
                cell = row.createCell(0);
                cell.setCellValue("内存利用率");
                cell.setCellStyle(style_temp);



                row = sheet.createRow(i);

                cell = row.createCell(0);
                cell.setCellValue("时间");
                cell.setCellStyle(style_temp);

                cell = row.createCell(1);
                cell.setCellValue("平均");
                cell.setCellStyle(style_temp);
                sheet.addMergedRegion(new CellRangeAddress(i, i, 1, 2));


                cell = row.createCell(3);
                cell.setCellValue("最大");
                cell.setCellStyle(style_temp);
                sheet.addMergedRegion(new CellRangeAddress(i, i, 3, 4));


                cell = row.createCell(5);
                cell.setCellValue("最小");
                cell.setCellStyle(style_temp);
                sheet.addMergedRegion(new CellRangeAddress(i, i, 5, 6));

                i++;
                itemid = ((JSONArray) getItemByHostidAndKey(hostids, "vm.memory.utilization").get("result")).getJSONObject(0).getString("itemid");  //根据键值获得内存的使用率
                JSONArray array1 = (JSONArray) getTrendByItemid(itemid).get("result");
                // 通过clock排序
                array1.sort(Comparator.comparing(obj1 -> {
                    Integer value = ((JSONObject) obj1).getIntValue("clock");
                    return value;
                }).reversed());
                JSONObject arr_obj1 = (JSONObject) array1.get(0);
                Long num1 = Long.valueOf(arr_obj1.get("clock").toString());
                for (Iterator iterator1 = array1.iterator(); iterator1.hasNext(); ) {
                    JSONObject obj1 = (JSONObject) iterator1.next();
                    if ((Long.valueOf(obj1.get("clock").toString()) + 86400l) >= num1) { //一个周的数据
                        sheet.addMergedRegion(new CellRangeAddress(i, i, 1, 2));
                        sheet.addMergedRegion(new CellRangeAddress(i, i, 3, 4));
                        sheet.addMergedRegion(new CellRangeAddress(i, i, 5, 6));
                        row = sheet.createRow(i);
                        i++;
                        cell = row.createCell(0);
                        cell.setCellValue(DateUtils.SecondTimeStamp2Date(obj1.get("clock").toString()));    //秒级别的时间戳转为年月日时分秒
                        cell.setCellStyle(style);

                        cell = row.createCell(1);
                        cell.setCellValue(obj1.get("value_avg").toString());            //获得平均数据
                        cell.setCellStyle(style);

                        cell = row.createCell(3);
                        cell.setCellValue(obj1.get("value_max").toString());            //获得最大值
                        cell.setCellStyle(style);

                        cell = row.createCell(5);
                        cell.setCellValue(obj1.get("value_min").toString());            //获得最小值
                        cell.setCellStyle(style);
                    } else
                        break;
                }


                //磁盘利用率
                row = sheet.createRow(i);
                sheet.addMergedRegion(new CellRangeAddress(i, i, 0, 6));
                i++;
                cell = row.createCell(0);
                cell.setCellValue("磁盘利用率");
                cell.setCellStyle(style_temp);


                row = sheet.createRow(i);

                cell = row.createCell(0);
                cell.setCellValue("时间");
                cell.setCellStyle(style_temp);

                cell = row.createCell(1);
                cell.setCellValue("平均");
                cell.setCellStyle(style_temp);
                sheet.addMergedRegion(new CellRangeAddress(i, i, 1, 2));


                cell = row.createCell(3);
                cell.setCellValue("最大");
                cell.setCellStyle(style_temp);
                sheet.addMergedRegion(new CellRangeAddress(i, i, 3, 4));

                cell = row.createCell(5);
                cell.setCellValue("最小");
                cell.setCellStyle(style_temp);
                sheet.addMergedRegion(new CellRangeAddress(i, i, 5, 6));

                i++;

                itemid = ((JSONArray) getItemByHostidAndKey(hostids, "vfs.fs.size[/,used]").get("result")).getJSONObject(0).getString("itemid");    //通过键值获得磁盘的使用率
                String itemid3 = ((JSONArray) getItemByHostidAndKey(hostids, "vfs.fs.size[/,total]").get("result")).getJSONObject(0).getString("itemid");   //通过键值获得磁盘的大小
                JSONArray array2 = (JSONArray) getTrendByItemid(itemid).get("result");
                JSONArray array3 = (JSONArray) getTrendByItemid(itemid3).get("result");
                array2.sort(Comparator.comparing(obj2 -> {
                    Integer value = ((JSONObject) obj2).getIntValue("clock");   //通过时间排序
                    return value;
                }).reversed());
                array3.sort(Comparator.comparing(obj3 -> {
                    Integer value = ((JSONObject) obj3).getIntValue("clock");
                    return value;
                }).reversed());

                JSONObject arr_obj2 = (JSONObject) array2.get(0);
                Long num2 = Long.valueOf(arr_obj2.get("clock").toString());
                Iterator iterator3 = array3.iterator();
                for (Iterator iterator2 = array2.iterator(); iterator2.hasNext(); ) {
                    JSONObject obj2 = (JSONObject) iterator2.next();
                    JSONObject obj3 = (JSONObject) iterator3.next();
                    if ((Long.valueOf(obj2.get("clock").toString()) + 86400l) >= num2) {    //是否大于一周
                        sheet.addMergedRegion(new CellRangeAddress(i, i, 1, 2));
                        sheet.addMergedRegion(new CellRangeAddress(i, i, 3, 4));
                        sheet.addMergedRegion(new CellRangeAddress(i, i, 5, 6));
                        row = sheet.createRow(i);
                        i++;
                        cell = row.createCell(0);
                        cell.setCellValue(DateUtils.SecondTimeStamp2Date(obj2.get("clock").toString()));
                        cell.setCellStyle(style);

                        cell = row.createCell(1);
                        cell.setCellValue(100*(double)Long.parseLong(obj2.get("value_avg").toString())/Long.parseLong(obj3.get("value_avg").toString()));
                        cell.setCellStyle(style);

                        cell = row.createCell(3);
                        cell.setCellValue(100*(double)Long.parseLong(obj2.get("value_max").toString())/Long.parseLong(obj3.get("value_max").toString()));
                        cell.setCellStyle(style);

                        cell = row.createCell(5);
                        cell.setCellValue(100*(double)Long.parseLong(obj2.get("value_min").toString())/Long.parseLong(obj3.get("value_min").toString()));
                        cell.setCellStyle(style);
                    } else
                        break;
                }

                //磁盘利用率
                row = sheet.createRow(i);
                sheet.addMergedRegion(new CellRangeAddress(i, i, 0, 6));
                i++;
                cell = row.createCell(0);
                cell.setCellValue("磁盘I/O速率");
                cell.setCellStyle(style_temp);



                row = sheet.createRow(i);

                cell = row.createCell(0);
                cell.setCellValue("时间");
                cell.setCellStyle(style_temp);

                cell = row.createCell(1);
                cell.setCellValue("平均");
                cell.setCellStyle(style_temp);
                sheet.addMergedRegion(new CellRangeAddress(i, i, 1, 2));


                cell = row.createCell(3);
                cell.setCellValue("最大");
                cell.setCellStyle(style_temp);
                sheet.addMergedRegion(new CellRangeAddress(i, i, 3, 4));

                cell = row.createCell(5);
                cell.setCellValue("最小");
                cell.setCellStyle(style_temp);
                sheet.addMergedRegion(new CellRangeAddress(i, i, 5, 6));
                i++;

                row = sheet.createRow(i);
                cell = row.createCell(0);
                cell.setCellStyle(style_temp);

                cell = row.createCell(1);
                cell.setCellValue("读速率(sps)");
                cell.setCellStyle(style_temp);

                cell = row.createCell(2);
                cell.setCellValue("写速率(sps)");
                cell.setCellStyle(style_temp);

                cell = row.createCell(3);
                cell.setCellValue("读速率(sps)");
                cell.setCellStyle(style_temp);

                cell = row.createCell(4);
                cell.setCellValue("写速率(sps)");
                cell.setCellStyle(style_temp);

                cell = row.createCell(5);
                cell.setCellValue("读速率(sps)");
                cell.setCellStyle(style_temp);

                cell = row.createCell(6);
                cell.setCellValue("写速率(sps)");
                cell.setCellStyle(style_temp);
                i++;


                String itemid5 = ((JSONArray) getItemByHostidAndKey(hostids, "vfs.dev.write").get("result")).getJSONObject(0).getString("itemid");  //通过键值获得写速率
                String itemid6 = ((JSONArray) getItemByHostidAndKey(hostids, "vfs.dev.read").get("result")).getJSONObject(0).getString("itemid");   //通过键值获得读速率
                JSONArray array5 = (JSONArray) getTrendByItemid(itemid5).get("result");
                JSONArray array6 = (JSONArray) getTrendByItemid(itemid6).get("result");
                array5.sort(Comparator.comparing(obj5 -> {
                    Integer value = ((JSONObject) obj5).getIntValue("clock");   //根据时间排序
                    return value;
                }).reversed());
                array6.sort(Comparator.comparing(obj6 -> {
                    Integer value = ((JSONObject) obj6).getIntValue("clock");
                    return value;
                }).reversed());

                JSONObject arr_obj5 = (JSONObject) array5.get(0);
                Long num5 = Long.valueOf(arr_obj5.get("clock").toString());
                Iterator iterator6 = array6.iterator();
                for (Iterator iterator5 = array5.iterator(); iterator5.hasNext(); ) {
                    JSONObject obj5 = (JSONObject) iterator5.next();
                    JSONObject obj6 = (JSONObject) iterator6.next();
                    if ((Long.valueOf(obj5.get("clock").toString()) + 86400l) >= num5) {    //是否为一周
                        row = sheet.createRow(i);
                        i++;
                        cell = row.createCell(0);
                        cell.setCellValue(DateUtils.SecondTimeStamp2Date(obj5.get("clock").toString()));
                        cell.setCellStyle(style);

                        cell = row.createCell(1);
                        cell.setCellValue(obj6.get("value_avg").toString());
                        cell.setCellStyle(style);
                        cell = row.createCell(2);
                        cell.setCellValue(obj5.get("value_avg").toString());
                        cell.setCellStyle(style);

                        cell = row.createCell(3);
                        cell.setCellValue(obj6.get("value_max").toString());
                        cell.setCellStyle(style);
                        cell = row.createCell(4);
                        cell.setCellValue(obj5.get("value_max").toString());
                        cell.setCellStyle(style);


                        cell = row.createCell(5);
                        cell.setCellValue(obj6.get("value_min").toString());
                        cell.setCellStyle(style);
                        cell = row.createCell(6);
                        cell.setCellValue(obj5.get("value_min").toString());
                        cell.setCellStyle(style);

                    } else
                        break;
                }


                //网卡流量
                List<Map<String,Object>> resultList = getNetData(hostids);
                for (int j = 0; j < resultList.size(); j++) {
                    itemid = resultList.get(j).get("itemid").toString();
                    JSONArray array7 = (JSONArray) getTrendByItemid(itemid).get("result");
                    array7.sort(Comparator.comparing(obj7 -> {
                        Integer value = ((JSONObject) obj7).getIntValue("clock");
                        return value;
                    }).reversed());
                    JSONObject arr_obj7 = (JSONObject) array7.get(0);
                    Long num7 = Long.valueOf(arr_obj7.get("clock").toString());
                    if ("0".equals(arr_obj7.get("value_avg").toString()))
                        continue;
                    row = sheet.createRow(i);
                    sheet.addMergedRegion(new CellRangeAddress(i, i, 0, 6));
                    i++;
                    cell = row.createCell(0);
                    cell.setCellValue(resultList.get(j).get("name")+"  网络接口流量");
                    cell.setCellStyle(style_temp);
                    row = sheet.createRow(i);

                    cell = row.createCell(0);
                    cell.setCellValue("时间");
                    cell.setCellStyle(style_temp);

                    cell = row.createCell(1);
                    cell.setCellValue("平均");
                    cell.setCellStyle(style_temp);
                    sheet.addMergedRegion(new CellRangeAddress(i, i, 1, 2));


                    cell = row.createCell(3);
                    cell.setCellValue("最大");
                    cell.setCellStyle(style_temp);
                    sheet.addMergedRegion(new CellRangeAddress(i, i, 3, 4));

                    cell = row.createCell(5);
                    cell.setCellValue("最小");
                    cell.setCellStyle(style_temp);
                    sheet.addMergedRegion(new CellRangeAddress(i, i, 5, 6));
                    i++;


                    for (Iterator iterator7 = array7.iterator(); iterator7.hasNext(); ) {
                        JSONObject obj7 = (JSONObject) iterator7.next();
                        if ((Long.valueOf(obj7.get("clock").toString()) + 86400l) >= num7) {
                            sheet.addMergedRegion(new CellRangeAddress(i, i, 1, 2));
                            sheet.addMergedRegion(new CellRangeAddress(i, i, 3, 4));
                            sheet.addMergedRegion(new CellRangeAddress(i, i, 5, 6));
                            row = sheet.createRow(i);
                            i++;
                            cell = row.createCell(0);
                            cell.setCellValue(DateUtils.SecondTimeStamp2Date(obj7.get("clock").toString()));
                            cell.setCellStyle(style);

                            cell = row.createCell(1);
                            cell.setCellValue(obj7.get("value_avg").toString());
                            cell.setCellStyle(style);

                            cell = row.createCell(3);
                            cell.setCellValue(obj7.get("value_max").toString());
                            cell.setCellStyle(style);

                            cell = row.createCell(5);
                            cell.setCellValue(obj7.get("value_min").toString());
                            cell.setCellStyle(style);
                        } else
                            break;
                    }

                }


                try {
                    FileOutputStream fos = new FileOutputStream(new File("f:\\性能分析报表.xls"));
                    wb.write(fos);
                    fos.close();
                } catch (Exception e) {
                    e.getMessage();
                }


            }else {
                HSSFWorkbook wb = new HSSFWorkbook();
                HSSFSheet sheet = wb.createSheet();
                HSSFRow row = sheet.createRow(0);
                sheet.setColumnWidth(0, 6000);

                sheet.setColumnWidth(1, 6000);
                sheet.setColumnWidth(2, 6000);

                sheet.setColumnWidth(3, 6000);
                sheet.setColumnWidth(4, 6000);

                sheet.setColumnWidth(5, 6000);
                sheet.setColumnWidth(6, 6000);
                HSSFCellStyle style = wb.createCellStyle();
                style.setAlignment(HSSFCellStyle.ALIGN_CENTER);


                HSSFCellStyle style_temp = wb.createCellStyle();
                style_temp.setFillForegroundColor((short) 13);
                style_temp.setAlignment(HSSFCellStyle.ALIGN_CENTER);
                style_temp.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
                // 第0行
                HSSFCell cell = row.createCell(i);
                sheet.addMergedRegion(new CellRangeAddress(i, i, 1, 6));
                i++;
                cell.setCellValue("设备名称");
                cell.setCellStyle(style_temp);
                cell = row.createCell(1);
                cell.setCellValue(resultMap.get(0).get("host").toString());
                //第1行
                row = sheet.createRow(i);
                sheet.addMergedRegion(new CellRangeAddress(i, i, 0, 6));
                i++;
                //CPU利用率
                cell = row.createCell(0);
                cell.setCellValue("CPU利用率");
                cell.setCellStyle(style_temp);


                //第2行
                row = sheet.createRow(i);

                cell = row.createCell(0);
                cell.setCellValue("时间");
                cell.setCellStyle(style_temp);

                cell = row.createCell(1);
                cell.setCellValue("平均");
                cell.setCellStyle(style_temp);
                sheet.addMergedRegion(new CellRangeAddress(i, i, 1, 2));

                cell = row.createCell(3);
                cell.setCellValue("最大");
                cell.setCellStyle(style_temp);
                sheet.addMergedRegion(new CellRangeAddress(i, i, 3, 4));

                cell = row.createCell(5);
                cell.setCellValue("最小");
                cell.setCellStyle(style_temp);
                sheet.addMergedRegion(new CellRangeAddress(i, i, 5, 6));

                i++;
                //共i行
                itemid = ((JSONArray) getItemByHostidAndKey(hostids, "system.cpu.util").get("result")).getJSONObject(0).getString("itemid");
                JSONArray array = (JSONArray) getTrendByItemid(itemid).get("result");
                array.sort(Comparator.comparing(obj -> {
                    Integer value = ((JSONObject) obj).getIntValue("clock");
                    return value;
                }).reversed());
                JSONObject arr_obj = (JSONObject) array.get(0);
                Long num = Long.valueOf(arr_obj.get("clock").toString());
                for (Iterator iterator = array.iterator(); iterator.hasNext(); ) {
                    JSONObject obj = (JSONObject) iterator.next();
                    if ((Long.valueOf(obj.get("clock").toString()) + 86400l) >= num) {
                        sheet.addMergedRegion(new CellRangeAddress(i, i, 1, 2));
                        sheet.addMergedRegion(new CellRangeAddress(i, i, 3, 4));
                        sheet.addMergedRegion(new CellRangeAddress(i, i, 5, 6));

                        row = sheet.createRow(i);
                        i++;
                        cell = row.createCell(0);
                        cell.setCellValue(DateUtils.SecondTimeStamp2Date(obj.get("clock").toString()));
                        cell.setCellStyle(style);

                        cell = row.createCell(1);
                        cell.setCellValue(obj.get("value_avg").toString());
                        cell.setCellStyle(style);

                        cell = row.createCell(3);
                        cell.setCellValue(obj.get("value_max").toString());
                        cell.setCellStyle(style);

                        cell = row.createCell(5);
                        cell.setCellValue(obj.get("value_min").toString());
                        cell.setCellStyle(style);
                    } else
                        break;
                }

                //内存利用率
                row = sheet.createRow(i);
                sheet.addMergedRegion(new CellRangeAddress(i, i, 0, 6));
                i++;
                cell = row.createCell(0);
                cell.setCellValue("内存利用率");
                cell.setCellStyle(style_temp);



                row = sheet.createRow(i);

                cell = row.createCell(0);
                cell.setCellValue("时间");
                cell.setCellStyle(style_temp);

                cell = row.createCell(1);
                cell.setCellValue("平均");
                cell.setCellStyle(style_temp);
                sheet.addMergedRegion(new CellRangeAddress(i, i, 1, 2));


                cell = row.createCell(3);
                cell.setCellValue("最大");
                cell.setCellStyle(style_temp);
                sheet.addMergedRegion(new CellRangeAddress(i, i, 3, 4));


                cell = row.createCell(5);
                cell.setCellValue("最小");
                cell.setCellStyle(style_temp);
                sheet.addMergedRegion(new CellRangeAddress(i, i, 5, 6));

                i++;
                itemid = ((JSONArray) getItemByHostidAndKey(hostids, "vm.memory.util").get("result")).getJSONObject(0).getString("itemid");//具体内容如上所示
                JSONArray array1 = (JSONArray) getTrendByItemid(itemid).get("result");
                array1.sort(Comparator.comparing(obj1 -> {
                    Integer value = ((JSONObject) obj1).getIntValue("clock");
                    return value;
                }).reversed());
                JSONObject arr_obj1 = (JSONObject) array1.get(0);
                Long num1 = Long.valueOf(arr_obj1.get("clock").toString());
                for (Iterator iterator1 = array1.iterator(); iterator1.hasNext(); ) {
                    JSONObject obj1 = (JSONObject) iterator1.next();
                    if ((Long.valueOf(obj1.get("clock").toString()) + 86400l) >= num1) {
                        sheet.addMergedRegion(new CellRangeAddress(i, i, 1, 2));
                        sheet.addMergedRegion(new CellRangeAddress(i, i, 3, 4));
                        sheet.addMergedRegion(new CellRangeAddress(i, i, 5, 6));
                        row = sheet.createRow(i);
                        i++;
                        cell = row.createCell(0);
                        cell.setCellValue(DateUtils.SecondTimeStamp2Date(obj1.get("clock").toString()));
                        cell.setCellStyle(style);

                        cell = row.createCell(1);
                        cell.setCellValue(obj1.get("value_avg").toString());
                        cell.setCellStyle(style);

                        cell = row.createCell(3);
                        cell.setCellValue(obj1.get("value_max").toString());
                        cell.setCellStyle(style);

                        cell = row.createCell(5);
                        cell.setCellValue(obj1.get("value_min").toString());
                        cell.setCellStyle(style);
                    } else
                        break;
                }

                //磁盘利用率
                row = sheet.createRow(i);
                sheet.addMergedRegion(new CellRangeAddress(i, i, 0, 6));
                i++;
                cell = row.createCell(0);
                cell.setCellValue("磁盘利用率");
                cell.setCellStyle(style_temp);

                row = sheet.createRow(i);

                cell = row.createCell(0);
                cell.setCellValue("时间");
                cell.setCellStyle(style_temp);

                cell = row.createCell(1);
                cell.setCellValue("平均");
                cell.setCellStyle(style_temp);
                sheet.addMergedRegion(new CellRangeAddress(i, i, 1, 2));


                cell = row.createCell(3);
                cell.setCellValue("最大");
                cell.setCellStyle(style_temp);
                sheet.addMergedRegion(new CellRangeAddress(i, i, 3, 4));

                cell = row.createCell(5);
                cell.setCellValue("最小");
                cell.setCellStyle(style_temp);
                sheet.addMergedRegion(new CellRangeAddress(i, i, 5, 6));
                i++;

                //初始化变量
                String itemidC1="",itemidC2="",itemidD1="",itemidD2="",itemidE1="",itemidE2="",itemidF1="",itemidF2="",itemidG1="",itemidG2="";
                JSONArray arrayC1=null,arrayC2=null,arrayD1=null,arrayD2=null,arrayE1=null,arrayE2=null,arrayF1=null,arrayF2=null,arrayG1=null,arrayG2=null;
                JSONArray arrC1=null,arrC2=null,arrD1=null,arrD2=null,arrE1=null,arrE2=null,arrF1=null,arrF2=null,arrG1=null,arrG2=null;
                Long numFinal = 0l;
                int count = 0;

                arrayC1 = ((JSONArray) getItemByHostidAndKey(hostids, "vfs.fs.size[C:,used]").get("result"));
                if (!arrayC1.isEmpty()){
                    count++;
                    arrayC2 = ((JSONArray) getItemByHostidAndKey(hostids, "vfs.fs.size[C:,total]").get("result"));//通过键值获得C盘的使用率
                    itemidC1 = arrayC1.getJSONObject(0).getString("itemid");
                    itemidC2 = arrayC2.getJSONObject(0).getString("itemid");
                    arrC1 = (JSONArray) getTrendByItemid(itemidC1).get("result");
                    arrC1.sort(Comparator.comparing(objC1 -> {
                        Integer value = ((JSONObject) objC1).getIntValue("clock");
                        return value;
                    }).reversed());
                    arrC2 = (JSONArray) getTrendByItemid(itemidC2).get("result");
                    arrC2.sort(Comparator.comparing(objC2 -> {
                        Integer value = ((JSONObject) objC2).getIntValue("clock");
                        return value;
                    }).reversed());
                    numFinal = Long.valueOf(((JSONObject) arrC1.get(0)).get("clock").toString());
                }

                arrayD1 = ((JSONArray) getItemByHostidAndKey(hostids, "vfs.fs.size[D:,used]").get("result"));       //通过键值获得D盘的使用率
                if (!arrayD1.isEmpty()){
                    count++;
                    arrayD2 = ((JSONArray) getItemByHostidAndKey(hostids, "vfs.fs.size[D:,total]").get("result"));
                    itemidD1 = arrayD1.getJSONObject(0).getString("itemid");
                    itemidD2 = arrayD2.getJSONObject(0).getString("itemid");
                    arrD1 = (JSONArray) getTrendByItemid(itemidD1).get("result");
                    arrD1.sort(Comparator.comparing(objD1 -> {
                        Integer value = ((JSONObject) objD1).getIntValue("clock");
                        return value;
                    }).reversed());
                    arrD2 = (JSONArray) getTrendByItemid(itemidD2).get("result");
                    arrD2.sort(Comparator.comparing(objD2 -> {
                        Integer value = ((JSONObject) objD2).getIntValue("clock");
                        return value;
                    }).reversed());
                }

                arrayE1 = ((JSONArray) getItemByHostidAndKey(hostids, "vfs.fs.size[E:,used]").get("result"));
                if (!arrayE1.isEmpty()){
                    count++;
                    arrayE2 = ((JSONArray) getItemByHostidAndKey(hostids, "vfs.fs.size[E:,total]").get("result"));//通过键值获得E盘的使用率
                    itemidE1 = arrayE1.getJSONObject(0).getString("itemid");
                    itemidE2 = arrayE2.getJSONObject(0).getString("itemid");
                    arrE1 = (JSONArray) getTrendByItemid(itemidE1).get("result");
                    arrE1.sort(Comparator.comparing(objE1 -> {
                        Integer value = ((JSONObject) objE1).getIntValue("clock");
                        return value;
                    }).reversed());
                    arrE2 = (JSONArray) getTrendByItemid(itemidE2).get("result");
                    arrE2.sort(Comparator.comparing(objE2 -> {
                        Integer value = ((JSONObject) objE2).getIntValue("clock");
                        return value;
                    }).reversed());
                }

                arrayF1 = ((JSONArray) getItemByHostidAndKey(hostids, "vfs.fs.size[F:,used]").get("result"));//通过键值获得F盘的使用率
                if (!arrayF1.isEmpty()){
                    count++;
                    arrayF2 = ((JSONArray) getItemByHostidAndKey(hostids, "vfs.fs.size[F:,total]").get("result"));
                    itemidF1 = arrayF1.getJSONObject(0).getString("itemid");
                    itemidF2 = arrayF2.getJSONObject(0).getString("itemid");
                    arrF1 = (JSONArray) getTrendByItemid(itemidF1).get("result");
                    arrF1.sort(Comparator.comparing(objF1 -> {
                        Integer value = ((JSONObject) objF1).getIntValue("clock");
                        return value;
                    }).reversed());
                    arrF2 = (JSONArray) getTrendByItemid(itemidF2).get("result");
                    arrF2.sort(Comparator.comparing(objF2 -> {
                        Integer value = ((JSONObject) objF2).getIntValue("clock");
                        return value;
                    }).reversed());
                }

                arrayG1 = ((JSONArray) getItemByHostidAndKey(hostids, "vfs.fs.size[G:,used]").get("result"));//通过键值获得G盘的使用率
                if (!arrayG1.isEmpty()){
                    count++;
                    arrayG2 = ((JSONArray) getItemByHostidAndKey(hostids, "vfs.fs.size[G:,total]").get("result"));
                    itemidG1 = arrayG1.getJSONObject(0).getString("itemid");
                    itemidG2 = arrayG2.getJSONObject(0).getString("itemid");
                    arrG1 = (JSONArray) getTrendByItemid(itemidG1).get("result");
                    arrG1.sort(Comparator.comparing(objG1 -> {
                        Integer value = ((JSONObject) objG1).getIntValue("clock");
                        return value;
                    }).reversed());
                    arrG2 = (JSONArray) getTrendByItemid(itemidG2).get("result");
                    arrG2.sort(Comparator.comparing(objG2 -> {
                        Integer value = ((JSONObject) objG2).getIntValue("clock");
                        return value;
                    }).reversed());
                }

                Iterator iteratorC2 = arrC2.iterator();
                Iterator iteratorD1 = arrD1.iterator();
                Iterator iteratorD2 = arrD2.iterator();
                Iterator iteratorE1 = arrE1.iterator();
                Iterator iteratorE2 = arrE2.iterator();
                Iterator iteratorF1 = arrF1.iterator();
                Iterator iteratorF2 = arrF2.iterator();
                Iterator iteratorG1 = arrG1.iterator();
                Iterator iteratorG2 = arrG2.iterator();
                int temp = 0;
                for (Iterator iteratorC1 = arrC1.iterator(); iteratorC1.hasNext(); ) {
                    System.out.println(temp++);
                    Long avg_use = 0l , max_use = 0l , min_use = 0l;
                    Long avg_total = 0l , max_total = 0l , min_total = 0l;
                    JSONObject objC1 = (JSONObject) iteratorC1.next();
                    JSONObject objC2 = (JSONObject) iteratorC2.next();
                    JSONObject objD1 = (JSONObject) iteratorD1.next();
                    JSONObject objD2 = (JSONObject) iteratorD2.next();
                    JSONObject objE1 = (JSONObject) iteratorE1.next();
                    JSONObject objE2 = (JSONObject) iteratorE2.next();
                    JSONObject objF1 = (JSONObject) iteratorF1.next();
                    JSONObject objF2 = (JSONObject) iteratorF2.next();
                    JSONObject objG1 = (JSONObject) iteratorG1.next();
                    JSONObject objG2 = (JSONObject) iteratorG2.next();
                    if ((Long.valueOf(objC1.get("clock").toString()) + 86400l) >= numFinal) {
                        sheet.addMergedRegion(new CellRangeAddress(i, i, 1, 2));
                        sheet.addMergedRegion(new CellRangeAddress(i, i, 3, 4));
                        sheet.addMergedRegion(new CellRangeAddress(i, i, 5, 6));
                        row = sheet.createRow(i);
                        i++;
                        cell = row.createCell(0);
                        cell.setCellValue(DateUtils.SecondTimeStamp2Date(objC1.get("clock").toString()));
                        cell.setCellStyle(style);


                        if (!arrayC1.isEmpty()){
                            avg_use += Long.valueOf(objC1.get("value_avg").toString());
                            max_use += Long.valueOf(objC1.get("value_min").toString());
                            min_use += Long.valueOf(objC1.get("value_max").toString());
                            avg_total += Long.valueOf(objC2.get("value_avg").toString());
                            max_total += Long.valueOf(objC2.get("value_min").toString());
                            min_total += Long.valueOf(objC2.get("value_max").toString());
                        }

                        if (!arrayD1.isEmpty()){
                            avg_use += Long.valueOf(objD1.get("value_avg").toString());
                            max_use += Long.valueOf(objD1.get("value_min").toString());
                            min_use += Long.valueOf(objD1.get("value_max").toString());
                            avg_total += Long.valueOf(objD2.get("value_avg").toString());
                            max_total += Long.valueOf(objD2.get("value_min").toString());
                            min_total += Long.valueOf(objD2.get("value_max").toString());
                        }

                        if (!arrayE1.isEmpty()){
                            avg_use += Long.valueOf(objE1.get("value_avg").toString());
                            max_use += Long.valueOf(objE1.get("value_min").toString());
                            min_use += Long.valueOf(objE1.get("value_max").toString());
                            avg_total += Long.valueOf(objE2.get("value_avg").toString());
                            max_total += Long.valueOf(objE2.get("value_min").toString());
                            min_total += Long.valueOf(objE2.get("value_max").toString());
                        }

                        if (!arrayF1.isEmpty()){
                            avg_use += Long.valueOf(objF1.get("value_avg").toString());
                            max_use += Long.valueOf(objF1.get("value_min").toString());
                            min_use += Long.valueOf(objF1.get("value_max").toString());
                            avg_total += Long.valueOf(objF2.get("value_avg").toString());
                            max_total += Long.valueOf(objF2.get("value_min").toString());
                            min_total += Long.valueOf(objF2.get("value_max").toString());
                        }
                        if (!arrayG1.isEmpty()){
                            avg_use += Long.valueOf(objG1.get("value_avg").toString());
                            max_use += Long.valueOf(objG1.get("value_min").toString());
                            min_use += Long.valueOf(objG1.get("value_max").toString());
                            avg_total += Long.valueOf(objG2.get("value_avg").toString());
                            max_total += Long.valueOf(objG2.get("value_min").toString());
                            min_total += Long.valueOf(objG2.get("value_max").toString());
                        }


                        cell = row.createCell(0);
                        cell.setCellValue(DateUtils.SecondTimeStamp2Date(objC1.get("clock").toString()));
                        cell.setCellStyle(style);

                        //平均求和除以总磁盘数
                        cell = row.createCell(1);
                        cell.setCellValue(100*(double)avg_use/avg_total);
                        cell.setCellStyle(style);

                        cell = row.createCell(3);
                        cell.setCellValue(100*(double)max_use/max_total);
                        cell.setCellStyle(style);

                        cell = row.createCell(5);
                        cell.setCellValue(100*(double)min_use/min_total);
                        cell.setCellStyle(style);

                    } else
                        break;
                }

                //磁盘I/O速率
                row = sheet.createRow(i);
                sheet.addMergedRegion(new CellRangeAddress(i, i, 0, 6));
                i++;
                cell = row.createCell(0);
                cell.setCellValue("磁盘I/O速率");
                cell.setCellStyle(style_temp);



                row = sheet.createRow(i);

                cell = row.createCell(0);
                cell.setCellValue("时间");
                cell.setCellStyle(style_temp);

                cell = row.createCell(1);
                cell.setCellValue("平均");
                cell.setCellStyle(style_temp);
                sheet.addMergedRegion(new CellRangeAddress(i, i, 1, 2));


                cell = row.createCell(3);
                cell.setCellValue("最大");
                cell.setCellStyle(style_temp);
                sheet.addMergedRegion(new CellRangeAddress(i, i, 3, 4));

                cell = row.createCell(5);
                cell.setCellValue("最小");
                cell.setCellStyle(style_temp);
                sheet.addMergedRegion(new CellRangeAddress(i, i, 5, 6));
                i++;

                row = sheet.createRow(i);
                cell = row.createCell(0);
                cell.setCellStyle(style_temp);

                cell = row.createCell(1);
                cell.setCellValue("读速率(sps)");
                cell.setCellStyle(style_temp);

                cell = row.createCell(2);
                cell.setCellValue("写速率(sps)");
                cell.setCellStyle(style_temp);

                cell = row.createCell(3);
                cell.setCellValue("读速率(sps)");
                cell.setCellStyle(style_temp);

                cell = row.createCell(4);
                cell.setCellValue("写速率(sps)");
                cell.setCellStyle(style_temp);

                cell = row.createCell(5);
                cell.setCellValue("读速率(sps)");
                cell.setCellStyle(style_temp);

                cell = row.createCell(6);
                cell.setCellValue("写速率(sps)");
                cell.setCellStyle(style_temp);
                i++;

                String itemid5 = ((JSONArray) getItemByHostidAndKey(hostids, "perf_counter[\\2\\18]").get("result")).getJSONObject(0).getString("itemid");
                String itemid6 = ((JSONArray) getItemByHostidAndKey(hostids, "perf_counter[\\2\\16]").get("result")).getJSONObject(0).getString("itemid");
                JSONArray array5 = (JSONArray) getTrendByItemid(itemid5).get("result");
                JSONArray array6 = (JSONArray) getTrendByItemid(itemid6).get("result");
                array5.sort(Comparator.comparing(obj5 -> {
                    Integer value = ((JSONObject) obj5).getIntValue("clock");
                    return value;
                }).reversed());
                array6.sort(Comparator.comparing(obj6 -> {
                    Integer value = ((JSONObject) obj6).getIntValue("clock");
                    return value;
                }).reversed());

                JSONObject arr_obj5 = (JSONObject) array5.get(0);
                Long num5 = Long.valueOf(arr_obj5.get("clock").toString());
                Iterator iterator6 = array6.iterator();
                for (Iterator iterator5 = array5.iterator(); iterator5.hasNext(); ) {
                    JSONObject obj5 = (JSONObject) iterator5.next();
                    JSONObject obj6 = (JSONObject) iterator6.next();
                    if ((Long.valueOf(obj5.get("clock").toString()) + 86400l) >= num5) {
                        row = sheet.createRow(i);
                        i++;
                        cell = row.createCell(0);
                        cell.setCellValue(DateUtils.SecondTimeStamp2Date(obj5.get("clock").toString()));
                        cell.setCellStyle(style);

                        cell = row.createCell(1);
                        cell.setCellValue(obj6.get("value_avg").toString());
                        cell.setCellStyle(style);
                        cell = row.createCell(2);
                        cell.setCellValue(obj5.get("value_avg").toString());
                        cell.setCellStyle(style);

                        cell = row.createCell(3);
                        cell.setCellValue(obj6.get("value_max").toString());
                        cell.setCellStyle(style);
                        cell = row.createCell(4);
                        cell.setCellValue(obj5.get("value_max").toString());
                        cell.setCellStyle(style);


                        cell = row.createCell(5);
                        cell.setCellValue(obj6.get("value_min").toString());
                        cell.setCellStyle(style);
                        cell = row.createCell(6);
                        cell.setCellValue(obj5.get("value_min").toString());
                        cell.setCellStyle(style);

                    } else
                        break;
                }
                //windows网络接口流量数据
                List<Map<String,Object>> resultList = getNetData(hostids);
                for (int j = 0; j < resultList.size(); j++) {
                    itemid = resultList.get(j).get("itemid").toString();
                    JSONArray array7 = (JSONArray) getTrendByItemid(itemid).get("result");
                    array7.sort(Comparator.comparing(obj7 -> {
                        Integer value = ((JSONObject) obj7).getIntValue("clock");
                        return value;
                    }).reversed());
                    JSONObject arr_obj7 = (JSONObject) array7.get(0);
                    Long num7 = Long.valueOf(arr_obj7.get("clock").toString());
                    if ("0".equals(arr_obj7.get("value_avg").toString()))
                        continue;
                    row = sheet.createRow(i);
                    sheet.addMergedRegion(new CellRangeAddress(i, i, 0, 6));
                    i++;
                    cell = row.createCell(0);
                    cell.setCellValue(resultList.get(j).get("name")+"  网络接口流量");
                    cell.setCellStyle(style_temp);
                    row = sheet.createRow(i);

                    cell = row.createCell(0);
                    cell.setCellValue("时间");
                    cell.setCellStyle(style_temp);

                    cell = row.createCell(1);
                    cell.setCellValue("平均");
                    cell.setCellStyle(style_temp);
                    sheet.addMergedRegion(new CellRangeAddress(i, i, 1, 2));


                    cell = row.createCell(3);
                    cell.setCellValue("最大");
                    cell.setCellStyle(style_temp);
                    sheet.addMergedRegion(new CellRangeAddress(i, i, 3, 4));

                    cell = row.createCell(5);
                    cell.setCellValue("最小");
                    cell.setCellStyle(style_temp);
                    sheet.addMergedRegion(new CellRangeAddress(i, i, 5, 6));
                    i++;


                    for (Iterator iterator7 = array7.iterator(); iterator7.hasNext(); ) {
                        JSONObject obj7 = (JSONObject) iterator7.next();
                        if ((Long.valueOf(obj7.get("clock").toString()) + 86400l) > num7) {
                            sheet.addMergedRegion(new CellRangeAddress(i, i, 1, 2));
                            sheet.addMergedRegion(new CellRangeAddress(i, i, 3, 4));
                            sheet.addMergedRegion(new CellRangeAddress(i, i, 5, 6));
                            row = sheet.createRow(i);
                            i++;
                            cell = row.createCell(0);
                            cell.setCellValue(DateUtils.SecondTimeStamp2Date(obj7.get("clock").toString()));
                            cell.setCellStyle(style);

                            cell = row.createCell(1);
                            cell.setCellValue(obj7.get("value_avg").toString());
                            cell.setCellStyle(style);

                            cell = row.createCell(3);
                            cell.setCellValue(obj7.get("value_max").toString());
                            cell.setCellStyle(style);

                            cell = row.createCell(5);
                            cell.setCellValue(obj7.get("value_min").toString());
                            cell.setCellStyle(style);
                        } else
                            break;
                    }

                }

                try {
                    // 利用字节流的方式写进excel
                    FileOutputStream fos = new FileOutputStream(new File("f:\\性能分析报表.xls"));
                    // 写入
                    wb.write(fos);
                    // 关闭字节流
                    fos.close();
                } catch (Exception e) {
                    e.getMessage();
                }
            }
        } else { //linux
            HSSFWorkbook wb = new HSSFWorkbook();
            HSSFSheet sheet = wb.createSheet();
            HSSFRow row = sheet.createRow(0);
            sheet.setColumnWidth(0, 6000);
            sheet.setColumnWidth(1, 6000);
            sheet.setColumnWidth(2, 6000);
            sheet.setColumnWidth(3, 6000);
            HSSFCellStyle style = wb.createCellStyle();
            style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
            HSSFCellStyle style_temp = wb.createCellStyle();
            style_temp.setFillForegroundColor((short) 13);
            style_temp.setAlignment(HSSFCellStyle.ALIGN_CENTER);
            style_temp.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
            // 第0行
            HSSFCell cell = row.createCell(i);
            sheet.addMergedRegion(new CellRangeAddress(i, i, 1, 3));
            i++;
            cell.setCellValue("设备名称");
            cell.setCellStyle(style_temp);
            cell = row.createCell(1);
            cell.setCellValue(resultMap.get(0).get("host").toString());
            //第1行
            row = sheet.createRow(i);
            sheet.addMergedRegion(new CellRangeAddress(i, i, 0, 3));
            i++;
            //CPU利用率
            cell = row.createCell(0);
            cell.setCellValue("CPU利用率");
            cell.setCellStyle(style_temp);
            //第2行
            row = sheet.createRow(i);

            cell = row.createCell(0);
            cell.setCellValue("时间");
            cell.setCellStyle(style_temp);

            cell = row.createCell(1);
            cell.setCellValue("平均");
            cell.setCellStyle(style_temp);

            cell = row.createCell(2);
            cell.setCellValue("最大");
            cell.setCellStyle(style_temp);

            cell = row.createCell(3);
            cell.setCellValue("最小");
            cell.setCellStyle(style_temp);

            i++;
            itemid = ((JSONArray) getItemByHostidAndKey(hostids, "system.cpu.util").get("result")).getJSONObject(0).getString("itemid");    //注释同上，可查到
            JSONArray array = (JSONArray) getTrendByItemid(itemid).get("result");
            array.sort(Comparator.comparing(obj -> {
                Integer value = ((JSONObject) obj).getIntValue("clock");
                return value;
            }).reversed());
            JSONObject arr_obj = (JSONObject) array.get(0);
            Long num = Long.valueOf(arr_obj.get("clock").toString());
            for (Iterator iterator = array.iterator(); iterator.hasNext(); ) {
                JSONObject obj = (JSONObject) iterator.next();
                if ((Long.valueOf(obj.get("clock").toString()) + 86400l) >= num) {

                    row = sheet.createRow(i);
                    i++;
                    cell = row.createCell(0);
                    cell.setCellValue(DateUtils.SecondTimeStamp2Date(obj.get("clock").toString()));
                    cell.setCellStyle(style);

                    cell = row.createCell(1);
                    cell.setCellValue(obj.get("value_avg").toString());
                    cell.setCellStyle(style);

                    cell = row.createCell(2);
                    cell.setCellValue(obj.get("value_max").toString());
                    cell.setCellStyle(style);

                    cell = row.createCell(3);
                    cell.setCellValue(obj.get("value_min").toString());
                    cell.setCellStyle(style);
                } else
                    break;
            }

            //内存利用率
            row = sheet.createRow(i);
            sheet.addMergedRegion(new CellRangeAddress(i, i, 0, 3));
            i++;
            cell = row.createCell(0);
            cell.setCellValue("内存利用率");
            cell.setCellStyle(style_temp);



            row = sheet.createRow(i);

            cell = row.createCell(0);
            cell.setCellValue("时间");
            cell.setCellStyle(style_temp);

            cell = row.createCell(1);
            cell.setCellValue("平均");
            cell.setCellStyle(style_temp);


            cell = row.createCell(2);
            cell.setCellValue("最大");
            cell.setCellStyle(style_temp);


            cell = row.createCell(3);
            cell.setCellValue("最小");
            cell.setCellStyle(style_temp);

            i++;
            itemid = ((JSONArray) getItemByHostidAndKey(hostids, "vm.memory.util").get("result")).getJSONObject(0).getString("itemid");
            JSONArray array1 = (JSONArray) getTrendByItemid(itemid).get("result");
            array1.sort(Comparator.comparing(obj1 -> {
                Integer value = ((JSONObject) obj1).getIntValue("clock");
                return value;
            }).reversed());
            JSONObject arr_obj1 = (JSONObject) array1.get(0);
            Long num1 = Long.valueOf(arr_obj1.get("clock").toString());
            for (Iterator iterator1 = array1.iterator(); iterator1.hasNext(); ) {
                JSONObject obj1 = (JSONObject) iterator1.next();
                if ((Long.valueOf(obj1.get("clock").toString()) + 86400l) >= num1) {
                    row = sheet.createRow(i);
                    i++;
                    cell = row.createCell(0);
                    cell.setCellValue(DateUtils.SecondTimeStamp2Date(obj1.get("clock").toString()));
                    cell.setCellStyle(style);

                    cell = row.createCell(1);
                    cell.setCellValue(obj1.get("value_avg").toString());
                    cell.setCellStyle(style);

                    cell = row.createCell(2);
                    cell.setCellValue(obj1.get("value_max").toString());
                    cell.setCellStyle(style);

                    cell = row.createCell(3);
                    cell.setCellValue(obj1.get("value_min").toString());
                    cell.setCellStyle(style);
                } else
                    break;
            }

            List<Map<String,Object>> resultList = getNetData(hostids);
            for (int j = 0; j < resultList.size(); j++) {
                itemid = resultList.get(j).get("itemid").toString();
                JSONArray array7 = (JSONArray) getTrendByItemid(itemid).get("result");
                array7.sort(Comparator.comparing(obj7 -> {
                    Integer value = ((JSONObject) obj7).getIntValue("clock");
                    return value;
                }).reversed());
                JSONObject arr_obj7 = (JSONObject) array7.get(0);
                Long num7 = Long.valueOf(arr_obj7.get("clock").toString());
                if ("0".equals(arr_obj7.get("value_avg").toString()))
                    continue;
                row = sheet.createRow(i);
                sheet.addMergedRegion(new CellRangeAddress(i, i, 0, 3));
                i++;
                cell = row.createCell(0);
                cell.setCellValue(resultList.get(j).get("name")+"  网络接口流量");
                cell.setCellStyle(style_temp);
                row = sheet.createRow(i);

                cell = row.createCell(0);
                cell.setCellValue("时间");
                cell.setCellStyle(style_temp);

                cell = row.createCell(1);
                cell.setCellValue("平均");
                cell.setCellStyle(style_temp);


                cell = row.createCell(2);
                cell.setCellValue("最大");
                cell.setCellStyle(style_temp);

                cell = row.createCell(3);
                cell.setCellValue("最小");
                cell.setCellStyle(style_temp);
                i++;


                for (Iterator iterator7 = array7.iterator(); iterator7.hasNext(); ) {
                    JSONObject obj7 = (JSONObject) iterator7.next();
                    if ((Long.valueOf(obj7.get("clock").toString()) + 86400l) >= num7) {
                        row = sheet.createRow(i);
                        i++;
                        cell = row.createCell(0);
                        cell.setCellValue(DateUtils.SecondTimeStamp2Date(obj7.get("clock").toString()));
                        cell.setCellStyle(style);

                        cell = row.createCell(1);
                        cell.setCellValue(obj7.get("value_avg").toString());
                        cell.setCellStyle(style);

                        cell = row.createCell(2);
                        cell.setCellValue(obj7.get("value_max").toString());
                        cell.setCellStyle(style);

                        cell = row.createCell(3);
                        cell.setCellValue(obj7.get("value_min").toString());
                        cell.setCellStyle(style);
                    } else
                        break;
                }

            }


            try {
                FileOutputStream fos = new FileOutputStream(new File("f:\\性能分析报表.xls"));
                wb.write(fos);
                fos.close();
            } catch (Exception e) {
                e.getMessage();
            }
        }
        return true;
    }
    //通过hostid和key查找item信息
    @Override
    public Map<String, Object> getItemByHostidAndKey(String hostid, String key) {
        final String token = APIUtils.getToken();
        Map<String, Object> paramsMap = new HashMap<String, Object>(){{
            put("jsonrpc", "2.0");
            put("method", "item.get");
            put("id", 1);
            put("auth", token);
            put("params", new HashMap<String, Object>(){{
                put("output", "itemid");
                put("hostids", hostid);
                put("search",new HashMap<String,Object>(){{
                    put("key_",key);
                }});
            }});
        }};
        // 结果序列化
        Map<String, Object> responseMap = APIUtils.sendRequest(JSON.toJSONString(paramsMap, SerializerFeature.WriteMapNullValue));
        return responseMap;
    }
    //   修改后的网络接口
    @Override
    public Map<String, Object> getNetData_new(String hostId) {
        final String token = APIUtils.getToken();
        //获取与流量相关的监控项id
        final String[] outputs = new String[]{"itemid", "name"};
        Map<String, Object> netData = new HashMap<String, Object>(){{
            put("jsonrpc", "2.0");
            put("method", "item.get");
            put("id", 1);
            put("auth", token);
            put("params", new HashMap<String, Object>(){{
                put("output", outputs);     //定义输出
                put("hostids",hostId);
                put("search", new HashMap<String, Object>(){{
                    put("key_", "net.if");  //获得网络数据
                    put("type", "0");
                    put("value_type", "3");
                }});
            }});
        }};
        //  结果序列化
        Map<String, Object> responseOfNetData = APIUtils.sendRequest(JSON.toJSONString(netData, SerializerFeature.WriteMapNullValue));
        List<Map<String, Object>> netList = (List<Map<String, Object>>) responseOfNetData.get("result");
//      筛选出:Bits received 和 Bits sent两种流量数据
        List<String> itemList = new ArrayList<String>();
        String itemid = null;
        String name = null;
        List<Map<String, Object>> returnList = new ArrayList<Map<String, Object>>();
        //  重新封装数据
        for (int i = 0; i < netList.size(); i++){
            itemid = (String) netList.get(i).get("itemid");
            name = (String) netList.get(i).get("name");
            if(name.contains("Bits received") || name.contains("Bits sent")){
                itemList.add(itemid);
                String finalItemid = itemid;
                String finalName = name;
                Map<String, Object> items = new HashMap<String, Object>(){{
                    put("itemid", finalItemid);
                    put("name", finalName);
                    put("data", null);
                }};
                returnList.add(items);
            }
        }

//      通过监控项id查出历史数据
        final Integer limit = itemList.size() * 10;
        ArrayList<String> his_details = new ArrayList<>();
        his_details.add("itemid");
        his_details.add("clock");
        his_details.add("value");
        Map<String, Object> historyDataOfNet = new HashMap<String, Object>(){{
            put("jsonrpc", "2.0");
            put("method", "history.get");   //获得历史数据
            put("id", 1);
            put("auth", token);
            put("params", new HashMap<String, Object>(){{
                put("output", his_details);
                put("history",3);
                put("sortfield","clock");   //通过clock排序
                put("sortorder", "DESC");   //降序
                put("itemids",itemList);
                put("limit", limit);
            }});
        }};
        Map<String, Object> responseOfHistoryDataMap = APIUtils.sendRequest(JSON.toJSONString(historyDataOfNet, SerializerFeature.WriteMapNullValue));
        List<Map<String, Object>> resultList = (List<Map<String, Object>>) responseOfHistoryDataMap.get("result");
        //      调整格式
        for (Map<String, Object> temp : returnList){
            List<Map<String, Object>> datas = new ArrayList<Map<String, Object>>();
            for(Map<String, Object> historyData : resultList) {
                if (temp.get("itemid").equals(historyData.get("itemid"))){
                    DateUtils.formatListDate(historyData, "clock");
                    datas.add(new HashMap<String, Object>(){{
                        put("clock", historyData.get("clock"));
                        put("value", historyData.get("value"));
                    }});
                }
            }
            temp.put("data", datas);
        }
        Map<String, Object> reclist  = new HashMap<>();
        reclist.put("itemids",itemList);
        reclist.put("datalist",returnList);
        return reclist;
    }

    /**
     * 返回指定监控项的最新值
     * @param itemIds
     * @return
     */
    @Override
    public List<Map<String, Object>> getNewNetDataByItems(ArrayList<String> itemIds) {
        String token = APIUtils.getToken();

        String[] output = new String[]{"lastvalue","lastclock"};
        Map<String, Object> paramsMap = new HashMap<String, Object>(){{
            put("jsonrpc", "2.0");
            put("method", "item.get");
            put("id", 1);
            put("auth", token);
            put("params", new HashMap<String, Object>(){{
                put("output",output);
                put("itemids",itemIds); //筛选指定监控项的设备
            }});
        }};
        Map<String, Object> resultList = APIUtils.sendRequest(JSON.toJSONString(paramsMap, SerializerFeature.WriteMapNullValue));
        JSONArray itemsValue = (JSONArray) resultList.get("result");
        List<Map<String, Object>> newItemValuemList = new ArrayList<>();
        for (int i = 0; i < itemsValue.size(); i++) {
            Map<String,Object> cur_map = DateUtils.JsonToMap(itemsValue.getJSONObject(i));//将JSON格式转为Map格式
            Map<String, Object> res_map = new HashMap<>();
            res_map.put("value",cur_map.get("lastvalue"));
            res_map.put("clock",cur_map.get("lastclock"));
            res_map.put("itemid",cur_map.get("itemid"));
            newItemValuemList.add(res_map);
        }
        return newItemValuemList;
    }

    /**
     * 设置监控项原型的轮询时间
     * @param hostId
     * @param delay
     * @return
     */
    @Override
    public boolean setDelayAs(String hostId, String delay) {
        String token = APIUtils.getToken();
        String[] namelist = new String[]{"*Bits received*","*Bits sent*"};  //获得网络的发送和接受数据
        String[] output = new String[]{"itemid"};
        Map<String, Object> params = new HashMap<String, Object>(){{
            put("jsonrpc", "2.0");
            put("method", "itemprototype.get"); //获得itemprototype
            put("id", 1);
            put("auth", token);
            put("params", new HashMap<String, Object>(){{
                put("output", output);
                put("hostids",hostId);
                //put("delay","1s");
                put("search", new HashMap<String, Object>(){{
                    put("key_", "net.if");  //获得网络数据
                    put("type", "0");
                    put("value_type", "3");
                    put("name",namelist);   //过滤指定名称的设别
                }});
                put("searchWildcardsEnabled",true);
                put("searchByAny",true);
            }});
        }};
        //结果序列化
        Map<String, Object> resultMap = APIUtils.sendRequest(JSON.toJSONString(params, SerializerFeature.WriteMapNullValue));
        JSONArray protoItems = (JSONArray) resultMap.get("result");
        ArrayList<String> protoItemList = new ArrayList<>();
        for (int i = 0; i < protoItems.size(); i++) {
            Map<String,Object> cur_map = DateUtils.JsonToMap(protoItems.getJSONObject(i)); // JSON转为Map格式
            protoItemList.add((String) cur_map.get("itemid"));
        }

        for (int i = 0; i < protoItemList.size(); i++) {
            String protoItem = protoItemList.get(i);
            Map<String, Object> protoParams = new HashMap<String, Object>(){{
                put("jsonrpc", "2.0");
                put("method", "itemprototype.update");
                put("id", 1);
                put("auth", token);
                put("params", new HashMap<String, Object>(){{
                    put("output", "extend");
                    put("itemid",protoItem);
                    put("delay",delay);
                }});
            }};
            Map<String, Object> resultProtoMap = APIUtils.sendRequest(JSON.toJSONString(protoParams, SerializerFeature.WriteMapNullValue));
            // 返回结果
            if (resultProtoMap == null){
                return false;
            }
        }
        return true;
    }

    /**
     * 修改后的SNMP网络接口
     * @param hostId
     * @param itemName
     * @return
     */
    @Override
    public Map<String, Object> getNetOfSnmpByName_new(String hostId, String itemName) {
        //获得token令牌
        final String token = APIUtils.getToken();
        final String[] outputs = new String[]{"itemid", "name"};
        Map<String, Object> value_typeMap = new HashMap<String, Object>(){{
            put("jsonrpc", "2.0");
            put("method", "item.get");
            put("id", 1);
            put("auth", token);
            put("params", new HashMap<String, Object>(){{
                put("output", outputs); //指定输出
                put("hostids", hostId);
                put("search", new HashMap<String, Object>(){{
                    put("name", itemName);  //通过监控项名称筛选数据
                }});
            }});
        }};
        Map<String, Object> ItemMap = APIUtils.sendRequest(JSON.toJSONString(value_typeMap, SerializerFeature.WriteMapNullValue));
        List<Map<String, Object>> ItemList = (List<Map<String, Object>>) ItemMap.get("result");

        //获取数据类型
        //筛选
        List<String> newItemIdList = new ArrayList<String>();
        String itemid = null;
        String name = null;
        List<Map<String, Object>> returnList = new ArrayList<Map<String, Object>>();
        String[] itemlist = new String[ItemList.size()+1];
        for (int i = 0; i < ItemList.size(); i++){
            itemid = (String) ItemList.get(i).get("itemid");
            name = (String) ItemList.get(i).get("name");
            itemlist[i] = itemid;
            if(name.contains("Bits received") || name.contains("Bits sent")){   //获得网络的接受和发送数据
                newItemIdList.add(itemid);
                String finalItemid = itemid;
                String finalName = name;
                Map<String, Object> items = new HashMap<String, Object>(){{
                    put("itemid", finalItemid);
                    put("name", finalName);
                    put("data", null);
                }};
                returnList.add(items);
            }
        }

        final Integer limit = newItemIdList.size() * 10;
        Map<String, Object> historyDataOfNet = new HashMap<String, Object>(){{
            put("jsonrpc", "2.0");
            put("method", "history.get");       // 获得历史数据
            put("id", 1);
            put("auth", token);
            put("params", new HashMap<String, Object>(){{
                put("output", "extend");
                put("history",3);
                put("sortfield","clock");   //根据clock排序
                put("sortorder", "DESC");   //降序
                put("itemids",newItemIdList);   //只包含指定监控项
                put("limit", limit);        //定义了limit个
            }});
        }};
        Map<String, Object> responseOfHistoryDataMap = APIUtils.sendRequest(JSON.toJSONString(historyDataOfNet, SerializerFeature.WriteMapNullValue));
        List<Map<String, Object>> resultList = (List<Map<String, Object>>) responseOfHistoryDataMap.get("result");
//      调整格式
        for (Map<String, Object> temp : returnList){
            // 重新封装数据
            List<Map<String, Object>> datas = new ArrayList<Map<String, Object>>();
            for(Map<String, Object> historyData : resultList) {
                if (temp.get("itemid").equals(historyData.get("itemid"))){
                    DateUtils.formatListDate(historyData, "clock");
                    datas.add(new HashMap<String, Object>(){{
                        put("clock", historyData.get("clock"));
                        put("value", historyData.get("value"));
                    }});
                }
            }
            temp.put("data", datas);
        }
        Map<String, Object> reclist  = new HashMap<>();
        reclist.put("itemids",itemlist);
        reclist.put("datalist",returnList);
        return reclist;
    }

    /**
     * 根据hostid查询服务器是Windows还是Linux
     * @param hostId
     * @return
     */
    @Override
    public int getAgentTypeByHostid(String hostId) {
        List<String> output = new ArrayList<>();
        output.add("lastvalue");
        // 获得token令牌
        final String token = APIUtils.getToken();
        Map<String, Object> dataMap = new HashMap<String, Object>(){{
            put("jsonrpc", "2.0");
            put("method", "item.get");
            put("id", 1);
            put("auth", token);
            put("params", new HashMap<String, Object>(){{
                put("output", output);
                put("hostids", hostId);
                put("search",new HashMap<String,Object>(){{
                    put("key_","system.uname");     //根据键值查找
                }});
            }});
        }};

        Map<String, Object> responseMap = APIUtils.sendRequest(JSON.toJSONString(dataMap, SerializerFeature.WriteMapNullValue));
        List<Map<String, Object>> resultList = (List<Map<String, Object>>) responseMap.get("result");
        // 1为Windows 0为Linux -1为其他
        if (resultList.get(0).get("lastvalue").toString().contains("Windows")){
            return 1;
        }else if (resultList.get(0).get("lastvalue").toString().contains("Linux")){
            return 0;
        }else{
            return -1;
        }
    }

    /**
     * 通过主机hostid获得监控项信息
     * @param hostid
     * @return
     */
    @Override
    public int getItemsByHostID(String hostid) {
        // 获得token令牌
        final String token = APIUtils.getToken();
        Map<String, Object> paramsMap = new HashMap<String, Object>(){{
            put("jsonrpc", "2.0");
            put("method", "template.get");  //获得模板
            put("id", 1);
            put("auth", token);
            put("params", new HashMap<String, Object>(){{
                put("hostids",hostid);
                put("output","templateid");
            }});
        }};
        // 结果序列化
        Map<String, Object> responseMap = APIUtils.sendRequest(JSON.toJSONString(paramsMap, SerializerFeature.WriteMapNullValue));
        int flag = 1;
        if(responseMap.get("result") != null){
            List<Map<String,String>> result =  (List<Map<String,String>>)responseMap.get("result");
            // 判断模板
            if("10081".equals(result.get(0).get("templateid"))){
                flag = 0;// windows
            }else if("10001".equals(result.get(0).get("templateid"))){
                flag = 1;// Linux
            }
        }
        return flag;
    }

    /**
     * 获得当前可用的设备
     * @return
     */
    @Override
    public List<Map<String, Object>> getAvailAllOnlineHost() {
        DemoServiceImpl demo = new DemoServiceImpl();
        List<Map<String,Object>> resultList = demo.getAllOnlineHost();
        for (int i = 0; i < resultList.size(); i++) {
            if ("1".equals(resultList.get(i).get("snmp_available")) || "1".equals(resultList.get(i).get("available")))
                continue;
            resultList.remove(i);
            i--;
        }
        // 返回所有可用的设备信息
        return resultList;
    }

    /**
     * 高负载接口 返回 cpu 内存 磁盘占用率
     * @param sortfield
     * @return
     */

    @Override
    public List<List<String>> getHighLoadHostList_cpu_mem_disk(String sortfield) {
        String token = APIUtils.getToken();
        List<Map<String,Object>> result_sort = new ArrayList<>();

        List<Map<String,Object>> hostids = new ArrayList<>();
        hostids = hostService.get_all_host_imporant(token);
        List<Map<String,Object>> hostids_snmp = hostService.get_all_snmp_host_imporant(token);

        JSONArray JSON_hostids = JSON.parseArray(String.valueOf(hostids));
        JSONArray JSON_snmp_hostids = JSON.parseArray(String.valueOf(hostids_snmp));
        // 隐去网络设备
        // JSONArray JSON_snmp_hostids = new JSONArray();

        Set<String> hostid_list = new HashSet<>();
        for (int i = 0; i < JSON_hostids.size(); i++) {
            JSONObject hostid = JSON.parseObject(JSON_hostids.getString(i));
            hostid_list.add(hostid.getString("hostid"));
        }
        for (int i = 0; i < JSON_snmp_hostids.size(); i++) {
            JSONObject hostid = JSON.parseObject(JSON_snmp_hostids.getString(i));
            hostid_list.add(hostid.getString("hostid"));
        }

        if (sortfield.equals("CPUUtilization")){    // 判断是否为cpu利用率
            List<Map<String, Object>> filteResultList = itemService.get_cup_item(token, new ArrayList<>(hostid_list));
            // 转换为JSONArray
            JSONArray jsonArray = JSONArray.parseArray(String.valueOf(filteResultList));

            List<Map<String,Object>> result_list = new ArrayList<>();

            // 遍历jsons数组对象，
            for (int i = 0; i < jsonArray.size(); i++) {
                Map<String, Object> result_map = new HashMap<>();
                // JSONArray 转为 JSONObject对象
                JSONObject cur_object = JSON.parseObject(jsonArray.getString(i));
                Map<String, Object> cur_map = DateUtils.JsonToMap(cur_object);
                result_map.put("hostid",cur_map.get("hostid"));
                String cur_key = (String) cur_map.get("key_");
                if (cur_key.contains("system.cpu.util")){   // 是否包含该键值
                    result_map.put("cpu_value",cur_map.get("lastvalue"));
                }
                result_list.add(result_map);
            }
            MonitorService monitorService = new MonitorServiceImpl();
            // 测试类型
            List<Map<String,Object>> sortresultList;
            // 按照cpu排序
            sortresultList= monitorService.sortList(result_list,"cpu_value");
            int count = sortresultList.size();
            if (count < 5) {
                sortresultList = sortresultList.subList(0,count);
            }else{
                sortresultList = sortresultList.subList(0,5);
            }
            for (int i = 0; i < sortresultList.size(); i++) {
                String hostid = (String) sortresultList.get(i).get("hostid");
                // 通过设备hostid获得cpu和内存信息
                Map<String, Object> rec_item = itemService.get_cup_and_mem_disk_item_byid(hostid, token);
                result_sort.add(rec_item);
            }
        }else{
            // 通过设备hostid（不止一个）获得监控项信息
            List<Map<String, Object>> filteResultList = itemService.get_mem_item(token,new ArrayList<>(hostid_list));
            // 转换为JSONArray
            JSONArray jsonArray = JSONArray.parseArray(String.valueOf(filteResultList));
            List<Map<String,Object>> result_list = new ArrayList<>();
            // 遍历jsons数组对象，
            for (int i = 0; i < jsonArray.size(); i++) {
                Map<String,Object> result_map = new HashMap<>();
                JSONObject cur_object = JSON.parseObject(jsonArray.getString(i));
                Map<String,Object> cur_map = DateUtils.JsonToMap(cur_object);
                result_map.put("hostid",cur_map.get("hostid"));
                String cur_key = (String) cur_map.get("key_");
                if (cur_key.contains("vm.memory.util")){
                    result_map.put("memory_value", cur_map.get("lastvalue"));    //获得内存的值
                }
                result_list.add(result_map);
            }
            MonitorService monitorService = new MonitorServiceImpl();
            // 测试类型
            List<Map<String,Object>> sortresultList;
            // 按照cpu排序
            sortresultList= monitorService.sortList(result_list,"memory_value");
            int count = sortresultList.size();
            if (count < 5) {
                sortresultList = sortresultList.subList(0,count);
            }else{
                sortresultList = sortresultList.subList(0,5);
            }
            for (int i = 0; i < sortresultList.size(); i++) {
                String hostid = (String) sortresultList.get(i).get("hostid");
                // 通过设备hostid获得cpu和内存信息
                Map<String, Object> rec_item = itemService.get_cup_and_mem_disk_item_byid(hostid, token);
                result_sort.add(rec_item);
            }
        }

        DecimalFormat df = new DecimalFormat("0.00");

        // 返回列表形式
        ArrayList<List<String>> resList = new ArrayList<>();

        for (Map<String, Object> stringObjectMap : result_sort) {
            // 需要的四个参数
            String[] itemString = new String[4];
            Iterator<Map.Entry<String, Object>> it = stringObjectMap.entrySet().iterator();
            while (it.hasNext()){
                Map.Entry<String, Object> entry = it.next();
                String itemkey = entry.getKey();
                if ("cpuUtilization".equals(itemkey)) {
                    String cpu_util = df.format(Double.valueOf(stringObjectMap.get("cpuUtilization").toString()));  //格式化cpu利用率
                    entry.setValue(cpu_util);
                    itemString[1] = cpu_util;
                }else if("memUtilization".equals(itemkey)) {
                    String memory_util = df.format(Double.valueOf(stringObjectMap.get("memUtilization").toString()));    //格式化内存利用率
                    entry.setValue(memory_util);
                    itemString[2] = memory_util;
                }else if ("diskUtilization".equals(itemkey)) {
                    String disk_util = df.format(Double.valueOf(stringObjectMap.get("diskUtilization").toString()));    //格式化内存利用率
                    entry.setValue(disk_util);
                    itemString[3] = disk_util;
                }else if ("hostname".equals(itemkey)) {
                    itemString[0] = stringObjectMap.get("hostname").toString();
                }
            }
            resList.add(Arrays.asList(itemString));
        }

        return resList;
    }


    /**
     * 数据过滤器
     * @param resultList
     * @return
     */
    public List<Map<String,Object>> filterItemdata_cpu_new(List<Map<String, Object>>  resultList) {
        List<Map<String,Object>> filterResultList = new ArrayList<>();
//        JSONObject JSON_result = JSON.parseObject(String.valueOf(resultList));

        for(int i=0; i< resultList.size(); i++){
            Map<String,Object> finaldata = new HashMap<>();
            finaldata.put("hostname",resultList.get(i).get("hostname"));
            finaldata.put("hostid",resultList.get(i).get("hostid"));
            // 组装ip+port
            List<Map<String, Object>> ipAndport = (List<Map<String,Object>>)resultList.get(i).get("interfaces");
//            System.out.println("接口：" +ipAndport);
            String ip = ipAndport.get(0).get("ip").toString();
            String port = ipAndport.get(0).get("port").toString();
            String hostinterface = ip + ":" + port;
            finaldata.put("hostinterface",hostinterface);
            finaldata.put("ip",ip);

            String cpuvalue = resultList.get(i).get("cpu_value").toString(); //获得cpu的值
            finaldata.put("CPUUtilization",cpuvalue);


//            if(!finaldata.containsKey("MemoryUtilization")){
//                finaldata.put("MemoryUtilization",0);
//            }
//            if(!finaldata.containsKey("CPUUtilization")){
//                finaldata.put("CPUUtilization",0);
//            }
            filterResultList.add(finaldata);
        }
        return filterResultList;
    }
}
